Members of the class
The members of a class can be divided into three main categories: fields, methods, and properties
In all members, only the contents of the normal field are saved in the object, that is: how many objects are created based on this class, and how many normal fields are in memory. Other members are saved in the class, that is, only one copy is created in memory, regardless of the number of objects.
First, the field
Fields contain static fields and normal fields, static fields belong to classes, normal fields belong to objects
class School (object): # static fields Munbers = 0 def__init__(self, name): # normal field self.name = name# Access Ordinary field by object obj1 = School (' Tsinghua ')print (Obj1.name)
Obj2 = School (' pking ') print(obj2.name)
# direct access to static fields through classes Print (school.munbers)
A static field saves only one copy of the class, whereas a normal field needs to hold one copy of each object. If each object has the same field, you can save the field as a static field
Second, the method
Methods include common methods, static methods, class methods, and three methods are stored in the class, the difference is the way the call is different
- Normal method: Called by the object; at least one self parameter; When the normal method is executed, the object that invokes the method is automatically assigned the value to auto;
- Class method: Called by the class; at least one CLS parameter; When the class method is executed, the class that invokes the method is automatically copied to the CLS;
- Static methods: Called by the class, no default parameters;
classFoo (object):def __init__(self, name): Self.name=namedefOrd_method (self):"""define a common method, with at least one self in the parameter""" Print("Common Methods") Print(self.name) @classmethoddefClass_method (CLS):"""defines a class method that has a parameter as long as it has a CLS and is @classmethod decorated""" Print("class Method") @staticmethoddefStatic_method ():"""defines a static method with parameters that cannot have self and are decorated with @staticmethod""" Print("Static Methods")#calling the normal methodobj = Foo ('Name') Obj.ord_method ()#Calling class methodsFoo.class_method ()#calling a static methodFoo.static_method ()
Third, attribute
Attributes are variants of a common method, and properties are defined in two ways.
Basic use of attributes
class Foo (object): def __init__ (self, name): Self.name = name @property def Show (self): Define a property "" " return Self.name # call properties by object obj = Foo ( " www " " result = obj.show print (Result)
The definition and invocation of a property is a few points to note:
- When defined, adds a @property adorner on the basis of a common method; property has only one self parameter
- When called, no parentheses are required
Method: Obj.func ()
Property: Obj.show
Note: The attribute has the meaning that it can be used to create and access the exact same illusion of the field when accessing the property.
Property is a variant of the method, and if there are no attributes in Python, the method can completely replace its functionality.
Two ways to define a property
- Decorate the method with an adorner definition
- A static field defined by a static field that defines a value as a Property object in a class
Defined by adorners
################ definition ###############classGoods (object): @propertydefPrice (self):Print '@property'@price. SetterdefPrice (self, value):Print '@price. Setter'@price. DeleterdefPrice (self):Print '@price. Deleter'################ Call ###############obj =Goods () Obj.price#automatically executes the @property decorated price method, and gets the return value of the methodObj.price= 123#automatically executes the @price. Setter-Modified price method, and assigns 123 to the parameters of the methoddelObj.price#automatic execution of @price. Deleter Modified Price Method
Defined by a static field
classFoo:defGet_bar (self):return 'Wenchong' #* Must be two parameters defSet_bar (self, value):return return 'Set Value'+valuedefDel_bar (self):return 'Wenchong'BAR = Property (Get_bar, Set_bar, Del_bar,'Description ...') obj=Foo () obj. BAR#automatically call the method defined in the first parameter: Get_barObj. BAR ="Alan" #automatically calls the method defined in the second parameter: Set_bar method and Passes "Alan" as a parameterdelFoo.bar#automatically call the method defined in the third parameter: Del_bar methodObj. Bae.__doc__ #automatically gets the value set in the fourth parameter: Description ...
Member modifiers
There are two forms for each member of a class
- Public members: accessible from anywhere
- Private Member: Accessible only within the class
Defined
Private members start with two underscores (special member exceptions), others are public members
class Foo (object): def __init__ (self): ' Public Members ' Self . __age ' Private Members '
Access
classFoo (object):def __init__(self): Self.name='Public Members'Self .__age='Private Members' defShow (self):Print(self.)__age) obj=Foo ()Print(Obj.name)#access to Public membersPrint(obj.__age)#access to private members, errorObj.show ()#indirect access to private members through public methods
You can force access to private fields by object. _ Class name __ Private field name, but this method is not recommended
Print (Obj._foo__age)
Methods, properties are defined to be accessed in a similar way
Special members of the class
1, __doc__
Represents the description of a class
class Foo (object): """ __doc__ What is displayed """ Pass
2, __model__ and __class__
- __MODEL__ module that represents the class of the current operation
- __CLASS__ represents the class of the current operation
3, __init__
Constructs a method that automatically fires when an object is created from a class
4, __del__
destructor, which automatically triggers execution when the object is freed in memory.
Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.
5, __call__
object is appended (), triggering execution
class Foo (object): def __call__ (Self, *args, * *Kwargs) : Print ('call') # First obj = foo () obj ()# Second foo () ()
6, __dict__
Show all members in a class or object
class Foo (object): def __init__ (self): ' Wenchong ' Print (Foo.) __dict__)
7, __str__
If the __str__ method is defined in a class, the return value of the method is output by default when the object is printed.
class Foo (object): def __str__ (self): return ' Str ' # creates an object from a class and prints the object obj = Foo ()print(obj)
8, __getitem__, __setitem__,__delitem__
Used for index operations, such as dictionaries. Each of the above represents the acquisition, setting, and deletion of data
classFoo (object):def __getitem__(self, item):Print(item)def __setitem__(self, Key, value):Print(key, value)def __delitem__(self, key):Print(key) obj=Foo () obj['name']#automatic execution of __getitem__ methodsobj['name'] ='Wenchong' #automatic execution of __setitem__ methodsdelobj['name']#automatic execution of __delitem__ methods
9, __iter__
For iterators, lists, dictionaries, and tuples can be used for loops because the type internally defines the __iter__
class Foo (object): def __iter__ (self): return iter ([11,22,33= Foo () for in obj: Print(i)
Python Learning-Object oriented 2