(This article is my own understanding)
Class Properties: Both the class itself and the instantiated object have
Instance properties: Only instantiated objects have, class itself (before not instantiated) is not
Reason:
Class attributes are written directly under class, for example
class A (): " I ' m class attr1 " Print (A.ATTR1) Print (dir (A)) " " I ' m class attr1[' __class__ ', ' __delattr__ ', ' __dict__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __ getattribute__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __init_subclass__ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __ne__ ', ' __ New__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __ Weakref__ ',
' attr1 '] " "
Instance properties require a prefix, such as
class A (): def __init__ (self): " I ' m attr2 "
When instantiating an object, the first call is the constructor __new__, and then the __init__ initialization object is called
classA ():def __new__(CLS, *args, * *Kwargs):"""Do something""" Print("I ' m new") returnSuper (A, CLS).__new__(CLS, *args, * *Kwargs)def __init__(Self, *args, * *Kwargs):Print("I ' m init") #Do somethingSELF.ATTR1 ='attr1'a=A ()#I ' m new#I ' m init
If __new__ does not return the parent's __new__ method (the topmost of course is object), the __init__ is not called
classA ():def __new__(CLS, *args, * *Kwargs):"""Do something""" Print("I ' m new") #return Super (A, CLS). __new__ (CLS, *args, **kwargs) def __init__(Self, *args, * *Kwargs):Print("I ' m init") #Do somethingSELF.ATTR1 ='attr1'a=A ()#I ' m new
When the object is not instantiated, there is no self to say. So the function that relies on self does not exist.
So instance properties are not in the class, only in the instance, and class properties can be in the instance
classA (): Attr1="I ' m attr1" def __init__(self): SELF.ATTR2="I ' m attr2"Print(A.ATTR1)#I ' m attr1Print(A.ATTR2)#Attributeerror:type object ' A ' has no attribute ' attr2 'Print(dir (A))#[' __class__ ', ' __new__ ' ... ' __weakref__ ', ' attr1 ']A =A ()Print(A.ATTR1)#I ' m attr1Print(A.ATTR2)#I ' m attr2Print(Dir (a))#[' __class__ ', ... ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' attr1 ', ' attr2 ']
Python class properties and instance properties are different