Private properties and methods (implementation encapsulation)
Python has no strict access control restrictions on class members, which is different from other object-oriented languages. About private properties and private methods The main points are as follows:
1. Generally, we agree that attributes starting with two underscores are private. Others are public.
2. Private properties (Methods) can be accessed inside the class
3. Private properties (Methods) cannot be accessed directly outside the class
4. The class name can be used outside the class_ Private property (method) name "access private property (method)"
#Test private properties and methods class Student: def __init__(self,name,age): self.name = name self.__age = age #Private property def __work(self): #Private method print("hardwork") print("age:{0}".format(self.__age)) e = Student("Zhang San",18) print(e.name) #print(e.age) print(e._Student__age) e._Student__work()
@property decorator
@Property can change the calling mode of a method into "property call". Here is a simple example,
#Test @ property usage class Employee: @property def salary(self): print("salary") return 10000 emp1 = Employee() #emp1.salary() print(emp1.salary)
Description of three object-oriented features
python is an object-oriented language, which also supports the three features of object-oriented programming
encapsulation
Hide the properties and implementation details of the object, and only provide necessary methods. It is equivalent to "encapsulating details" and only exposing "related calling methods" The "encapsulation" is realized by the way of "private attributes and private methods" above.
inherit
Inheritance can make subclasses have the characteristics of parent classes and improve the reusability of code. From design It is an incremental evolution. When the original parent class design remains unchanged, new functions can be added or existing algorithms can be improved.
polymorphic
Polymorphism means that the same method call will produce different behaviors due to different objects.
inherit
Syntax format
Python supports multiple inheritance. A subclass can inherit multiple parent classes. The inherited syntax format is as follows:
Class subclass class name (parent class 1 [, parent class 2,..]):
Class body
If no parent class is specified in the class definition, the default parent class is the object class. In other words, object is the parent class of all classes, which defines some default implementations common to all classes, such as:_ new_ ().
When you define a subclass, you must call the constructor of the parent class in its constructor. The calling format is as follows:
Parent class name_ jinit__ (self, parameter list)
#Basic use of test inheritance class Person: def __init__(self,name,age): self.name = name self.__age = age #Private property def say_age(self): print("Age 19") class Student(Person): def __init__(self,name,age,score): Person.__init__(self,name,age) #The initialization method of the parent class must be explicitly called, otherwise the interpreter will not call it self.score = score #Student -- > person -- > object class print(Student.mro()) s = Student("jack",19,90) s.say_age() print(s.name) #print(s.age) print(dir(s)) print(s._Person__age) #Calling the private property of the parent class
Inheritance and override of class members
1. Member inheritance: the subclass inherits all members of the parent class except the constructor.
2. Method Rewriting: subclasses can redefine the methods in the parent class q, which will override the methods of the parent class, also known as "Rewriting"
#Rewriting of test methods class Person: def __init__(self,name,age): self.name = name self.__age = age #Private property def say_age(self): print("My age:",self.__age) def say_introduce(self): print("When my name{0}".format(self.name)) class Student(Person): def __init__(self,name,age,score): Person.__init__(self,name,age) #The initialization method of the parent class must be explicitly called, otherwise the interpreter will not call it self.score = score def say_introduce(self): '''Override parent method''' print("Report to the teacher, my name is:{0}".format(self.name)) s =Student("jack",16,90) s.say_age() s.say_introduce()
dir() and mro()
The built-in function dir() allows us to easily see all the properties of the specified object
The inheritance hierarchy of this class can be output through the class method mro (or the class attribute mro).
Rewrite__ str__ () method
Object has a -_ str_ () method, which is used to return -- a description of the "object", corresponding to the built-in function str(). It is often used in the print0 method to help us view the information of the object- str_ () can be overridden
#Test rewriting object__ str__ () class Person: #Inherit object class by default def __init__(self,name,): self.name = name def __str__(self): return "my name is :{0}".format(self.name) p = Person("JCAK") print(p)
multiple inheritance
Python supports multiple inheritance. A subclass can have multiple "direct parent classes". In this way, it has the characteristics of "multiple parent classes". However, because this will be extremely complicated by the "overall level of the class", try to avoid using it.
super() gets the definition of the parent class
In the subclass, if we want to get the method of the parent class, we can do it through super(). super() represents the definition of the parent class, not the parent object.
polymorphic
Polymorphism means that the same method call may produce different behaviors due to different objects. Note the following 2 points about polymorphism:
1. Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes.
2. There are two necessary conditions for polymorphism: Inheritance and method rewriting
#polymorphic class Man: def eat(self): print("Eat when you are hungry") class Chinese(Man): def eat(self): print("Chinese people eat with chopsticks") class English(Man): def eat(self): print("The British eat with a fork") class Indian(Man): def eat(self): print("Indians eat with their hands") def ManEat(m): if isinstance(m,Man): m.eat() #Polymorphism is a method call, which calls different methods according to different objects else: print("Can't eat") ManEat(Chinese())
Overloading of special methods and special properties and operators
method | explain | example |
__init__ | Construction method | Object creation: p = Person() |
__del__ | Deconstruction method | Object recycling |
_-repr_ ,_ str_ | Printing, converting | print(a) |
__call__ | function call | a() |
__getattr__ | Dot operation | a.Xxx |
__setattr__ | Attribute assignment | a.xxx = value |
__getitem__ | Index operation | a[key] |
__setitem__ | Cable bow | assignment | a[key]=value |
__len__ | length | len(a) |
operator | Special method | explain |
Operator+ | _add__ | addition |
Operator- | _sub_ | subtraction |
<,<=,== | __It_ ,_ le_,_ eq_ | Comparison operator |
>,>=,!= | _gt_ ,_ _ge_ _ne_ | Comparison operator |
|,^,& | __or__ ,_ xor_ _and_ | Or, XOR, and |
<<,> > | _lshift_ ,_ _rshift_ | Move left and right |
*,/,%,// | _mul_ ,_truediv_ __mod_ _floordiv_ | Multiplication, floating-point division, modulo (remainder), integer division |
** | __pow__ | Exponential operation |
Special properties | meaning |
obj__dict__ | Object's attribute dictionary |
obj__class__ | The class to which the object belongs |
class.__bases_ | Base class tuple of class (multiple inheritance) |
class.__base_ | Base class of class |
class.__mro__ | Class hierarchy |
class. __subclasses_ () | Subclass list |
Shallow and deep copies of objects
#Shallow and deep copies of test objects import copy class MobilePhone: def __init__(self,cpu,screen): self.cpu = cpu self.screen = screen class CPU: def calculate(self): print("Start calculation") print("cpu Object:",self) class Screen: def show(self): print("Show a nice picture") print("screen Object:",self) #Test variable assignment c1 = CPU() c2 = c1 print(c1) print(c2) print("Test shallow copy") #Test shallow copy s1 = Screen() m1 = MobilePhone(c1,s1) m2 = copy.copy(m1) print(m1,m1.cpu,m1.screen) print(m2,m2.cpu,m2.screen) #Test deep copy print("Test deep copy") m3 = copy.deepcopy(m1) print(m1,m1.cpu,m1.screen) print(m2,m2.cpu,m2.screen)
combination
#Test combination class A1: def say_a1(self): print("a1") class B1(A1): def __init__(self): pass b1 = B1() b1.say_a1() class A2: def say_a2(self): print("a2") class B2: def __init__(self,a): self.a = a a2 = A2() b2 = B2(a2) b2.a.say_a2()