python的实例属性与类属性

不说废话,上代码(python3)。

class Cls:
    common = 7 #静态变量,在Cls的__dict__里面

    def __init__(self): #实例方法,在Cls的__dict__里面
        self.age = 5 #实例属性,在实例的__dict__

    def f(self): #实例方法,在Cls的__dict__里面
        return self.age

>>> dir(Cls)
['__class__', '__dict__', '__init__', 'common', 'f', ...]
>>> Cls.__dict__
mappingproxy({'common': 7, '__init__': , 'f': , '__dict__': , ...})
>>> Cls.__class__


>>> c=Cls()
>>> dir(c)
['__class__', '__dict__', '__init__', 'age', 'common', 'f']
>>> c.__dict__
{'age': 5}
>>> c.common = 1
>>> c.__dict__
{'age': 5, 'common': 1}
>>> c.__class__


#如何修改类的已有方法或者添加新方法?
>>> def g(x): return x.age + 1
>>> Cls.f = g #注意这里是Cls.f而不是c.f
>>> c.f()
6
#如果这样改会怎样?
>>> c.f = g
>>> c.f() #抛异常,缺少参数
>>> c.f(c) #OK,但是不方便

你可能感兴趣的:(python)