Python 面向对象编程基础:类、实例与属性操作
定义类与实例化对象
在 Python 中,类是创建对象的蓝图。通过 class 关键字可以定义一个新的类。类中可以包含类属性,这些属性默认由该类的所有实例共享。
class NetworkNode:
is_active = False
router1 = NetworkNode()
print(router1.is_active)
构造方法与状态初始化
在实际开发中,仅包含静态类属性的类往往不够用。为了在对象创建时赋予其独特的初始状态,我们需要使用 __init__() 魔法方法。该方法在每次实例化类时会自动触发,常用于绑定实例特有的属性。
class UserSession:
def __init__(self, username, session_id):
self.username = username
self.session_id = session_id
session_a = UserSession("admin", "8f7d9a2b")
print(session_a.username)
print(session_a.session_id)
需要注意的是,每次通过类创建新实例时,Python 解释器都会在后台自动调用 __init__() 方法。
实例方法与 self 引用
对象不仅可以拥有数据(属性),还可以拥有行为(方法)。实例方法是定义在类内部的函数,用于操作该对象的数据。在定义实例方法时,第一个参数必须是代表对象自身的引用,社区约定俗成将其命名为 self。
class PaymentGateway:
def __init__(self, merchant_id, currency):
self.merchant_id = merchant_id
self.currency = currency
def process_transaction(self, amount):
print(f"Processing {amount} {self.currency} for merchant {self.merchant_id}")
gateway = PaymentGateway("M9921", "USD")
gateway.process_transaction(150.00)
虽然 self 是标准规范,但它在语法层面上只是一个占位符。你可以使用任何合法的变量名来代替它,只要确保它是方法签名中的第一个参数即可,Python 会自动将当前实例传递给该参数。
class CacheItem:
def __init__(ctx, key, ttl):
ctx.key = key
ctx.ttl = ttl
def refresh(ctx):
print(f"Refreshing cache for key: {ctx.key}")
item = CacheItem("user_profile", 3600)
item.refresh()
属性的动态修改与销毁
Python 允许在运行时动态修改对象的属性值。此外,如果某些属性不再需要,可以使用 del 关键字将其从对象内存中移除。
# 更新属性值
item.ttl = 7200
# 移除特定属性
del item.key
同样地,del 关键字也可以用于彻底销毁整个对象实例。一旦对象被删除,再次访问该变量名将会引发 NameError 异常。
del item