一、类属性VS实例属性
类属性和实例属性都可以动态的创建!
1、访问类属性
类属性可以通过类或者实例来进行访问,但是类属性不能通过实例来进行更新。当通过实例对类属性进行更新时,会在实例中创建一个实例属性。
class MyClass(object):
version = 1.0
c = MyClass()
print(MyClass.version)
print(c.version)
MyClass.version = 1.1
c.version = 1.5 #这里不会更改类属性,而是创建一个实例属性
print(MyClass.version)
print(c.version)
输出:
1.0
1.0
1.1
1.5
2、从实例中访问类属性需谨慎
任何对实例属性的赋值都会创建一个实例属性(如果不存在该实例属性)并且对它赋值。因为python中的实例是可以动态的添加属性的。
二、static method VS class method
A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.
A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys()
, a classmethod, returns an instance of the subclass when called on a subclass:
classmethod能够访问类属性,但是staticmethod则不能。