Supplement to the previous section
When the class in which the object is created is not the way we want to do it, we know it should be found in its parent class, if there is a method we want to find in the parent class, and if we drop the following and include the method, how does the method be implemented?
Class A: def F1 (self): print ("A") def-xxx (self): print ("111") class B: def F1 (self): Self.xxx () print ("B") def xxx (self): print ("222") class C (): def f2 (self): print ("C") def xxx (self): print ("444") class D (c,b): def f (self): print ("D") obj = D () obj.f1 ()
We know that an object can execute its own construction method, so what if we want the object to execute its own construction method, and how to do the parent class's construction method?
1, super (current class name, self). __INIT__ () Recommended use
2. Parent class name. __init__ (self)
Class Annimal: def __init__ (self): self.name = "Animal" print ("construction Method a") class Cat (Annimal): def __init__ ( Self): self.tp = "Meow" Print ("construction method B") # Super (cat,self). __init__ () annimal.__init__ (self) obj = Cat () Print (obj.__dict__) #表示对象内所封装的成员构造方法B构造方法A {' name ': ' Animal ', ' TP ': ' Meow '}
Derived classes inherit from the parent class the methods that are included in the Init and methods found in the method ( the process of finding the source code )
If there is no __init__ constructor in the derived class, go to its parent class (must have an inheritance relationship)
Class Annimal: def __init__ (self): print ("construction Method A") def F1 (self): print ("111") class Cat (Annimal) : def __init__ (self): self.f1 () Print ("construction method B") super (cat,self). __init__ () obj = Cat () # Cat ( The __init__ method in cat is executed, and there is no F1 method in the __init__ method Self.f1 cat to go to Annimal to find 111 construction Method B construction Method A
by Reflection: by Class self-can find members of a class
objects can be found within the object and the members of the class can be found.
This chapter will focus on the members of the Python class, the member modifiers, the special members of the class
I. Members of the class
The members of a class can be divided into three main categories: fields, methods, attributes
Class Qwe: Age = Ten #静态字段 def __init__ (self,name): #构造方法 self.name = name # normal field def F1 ( Self): # normal method print ("123") @staticmethod #静态方法 def f2 (args,args1): print ("Zxx") @classmethod #类方法 def f3 (CLS): print (CLS) @property #特性 (forge a method into a field) def f4 ( Self): temp = self.name return temp @f4. Setter def f4 (self,value): print (value) Self.name = Valuea = Qwe ("111") A.f1 () Qwe.f2 () qwe.f3 () print (a.f4) qwe.f4 = 456print (a.f4)
Note: In all members, only the contents of the normal field are saved in the object, based on which multiple objects are created in the object, how many ordinary fields are in memory, and the other members are saved in the class, regardless of the number of objects, only one copy of the memory
1. Class Members
by but:
- Static field saves only one copy in memory
- Normal fields save one copy of each object
Fields are: Normal field: Normal field belongs to object, normal field is used when object has different label.
Static fields: Static fields belong to the class, and the things that exist in each object are saved in a class (parameters that are used by multiple methods)
Method is divided into: Normal method: Def xxx (self) must create an object to access the method
Static methods: You can have additional parameters @staticmethod do not need to create an object to access the method by adding @staticmethod before the method and not adding self to the method
def xxx ()
Class method: By adding @classmethod before the method and the method must have a CLS (the class name of the current class) @classmethod
def xxx (CLS)
Attributes: By adding @property to the method before the method is forged into a field (accessing the method as a field) the parameter can only be a self @property
Through the object. Method (without parentheses after method) obj.f1 def xxx (self)
The following is used to set the value
@property def f4 (self): temp = self.name return temp@f4.setterdef f4 (self,value):
Class Qwe: Age = Ten #静态字段, exists in class def __init__ (self,name): #构造方法, there is a class self.name = name # normal field, Existence object in def F1 (self): # Normal method, existence class in print ("123") @staticmethod #静态方法 def f2 (ARGS,ARGS1): print ("Zxx") @classmethod #类方法 def f3 (CLS): print (CLS) @property #特性 ( Forge a method into a field) def f4 (self): temp = self.name return temp @f4. Setter def f4 (self,value): Print (value) self.name = Valuea = Qwe ("111") A.f1 () qwe.f2 (All) qwe.f3 () print (a.f4) qwe.f4 = 456print (a.f4)
Rule: Own members to access (in addition to the ordinary methods in the class (itself can but we do not))
Access by class: Static fields, static methods, class methods (special cases of static methods)
Access through objects: Static fields, common methods of classes, attributes of classes
Member: Field: Static field (Each object has one copy), normal field (each object is different)
Method: Static method (without using object encapsulated content), normal method (using object encapsulated content), class method ()
Features: Common features (access by forging a method into a field)
Quick judgment call: There are self==> object calls
No self==> class calls
2. Modifiers for class members
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): self.name = ' public field ' Self.__foo = ' private field '
Static fields
public static fields: classes are accessible, inside classes can be accessed, and in derived classes
private static field: Only the class can be accessed internally;
Class C: def __init__ (self): Self.foo = "public Field" def func (self): Print Self.foo # class internal Access Class D (C): C14/>def Show (self): the print Self.foo # derived class accesses obj = C () Obj.foo # through the object access Obj.func () # class internal Access Obj_son = D (); obj_ Son.show () # Access in derived classes
Class C: def __init__ (self): Self.__foo = "private Field" def func (self): Print Self.__foo # class internal Access Class D (C):
def Show (self): the print Self.__foo # derived class accesses obj = C () Obj.__foo # through Object access ==> error Obj.func () # class internal Access ==> correct Obj_son = D (); Obj_son.show () # access ==> error in derived class
1, for their own private freedom to access, the derived class and the parent class can not access (meaning that in their own internal access)
Member modifiers: Public anywhere access
Private can only be accessed within themselves, or externally, indirectly, by accessing private
If you do not want to access private fields outside, you can also use the object _ Class name __ field (or method)
Some common special methods in object-oriented: __init__, __del__,
Class foo:__metaclass__ = mytype# indicates who created the Def __init__ (self): #r = Foo () instanced object print ("xxx") def __call__ (self,*args,** Kwargs): #r () Execute this method print ("XXX") return 1def __getitem__ (self, item): #r ["xxx"] and r[x:x] Execute this method print (item) def __ Setitem__ (self, Key, value): #r ["xxx"] = 123 Execute this method print (Key,value) def __delitem__ (self, key): #del r["xxx"] Execute this method print (key)
__dict__ get a member of a class or object, usage: xxx.__dict__
__doc__ getting comments
R = Foo () #在类后面加括号执行__init__
R () #在对象后面加括号执行__call__
m = Foo () () #先Foo () Instantiates an object execution __init__, and then executes the parentheses after the object __call__
Print (m) #获取对象加括号的返回值
2. Exception handling
In order to prevent the program to report some unknown errors, do not let the user see the Big Yellow Pages (error message), but can be converted to a human interface outside the class
INP = input ("Please enter content:") Try: #try里面就是捕获错误 num = Int (INP) print (num) except Indexerror as E: #IndexError Indicates catch index error (specific error) print ("index error") except Exception as E: #这里的e表示封装了错误信息的对象, Exception represents a collection of all types of errors, is the base class for all error classes print (e)
Object-oriented Advanced article