All members of the class have been described in more detail in the previous step, and there are two forms for each member of a class:
- Public members, accessible from anywhere
- Private members, only inside the class can the method
Private members and public members are defined differently : The first two characters are underlined when a private member is named. (except for special members, e.g. __init__, __call__, __dict__, etc.)
class C: def __init__ (self): ' Public Fields ' Self . __foo " Private Fields "
Private members and public members have different access restrictions :
Static fields
- public static fields: classes are accessible, inside classes can be accessed, and in derived classes
- private static fields: Only inside the class can be accessed
classC:name="public static fields" deffunc (self):PrintC.nameclassD (C):defShow (self):PrintC.namec.name#class Accessobj=C () obj.func ()#within the class can be accessedObj_son=D () obj_son.show ()#in a derived class, you can access
classC:__name="public static fields" deffunc (self):PrintC.__nameclassD (C):defShow (self):PrintC.__nameC.__name #class Access ==> errorobj=C () obj.func ()#The ==> within the class can access the correctObj_son=D () obj_son.show ()#==> errors can be accessed in derived classes
Normal field
- Public common fields: objects can be accessed, accessible within classes, and accessible in derived classes
- Private Normal field: Only within the class can be accessed;
PS: If you want to force access to a private field, you can access it through the object. _ Class name __ Private character Deming (for example: Obj._c__foo), and it is not recommended to force access to private members.
classC:def __init__(self): Self.foo="Public Fields" deffunc (self):PrintSelf.foo#Class internal AccessclassD (C):defShow (self):PrintSelf.foo # Accessing obj in a derived class=C () Obj.foo#Access by ObjectObj.func ()#Class internal AccessObj_son=D (); Obj_son.show ()#access in derived classes
classC:def __init__(self): self.__foo="Private Fields" deffunc (self):PrintSelf.foo#Class internal AccessclassD (C):defShow (self):PrintSelf.foo # Accessing obj in a derived class=C () obj.__foo #==> error through object accessObj.func ()#class internal access ==> correctObj_son=D (); Obj_son.show ()#accessing ==> errors in derived classes
Methods, properties are accessed in the same way that a private member can only be used inside a class
PS: If you want to access a private property, you can pass the object. _ Class __ Property name
Modifiers for Python class members