Hide object properties and implementation details , Only provide necessary methods for external . Is equivalent to “ The details are encapsulated ”, Exposure only “ Related call methods ”, Through the “ Private property 、 Private method ” The way , Realization “ encapsulation ”.
Python There are no strict access control restrictions on class members , This is different from other object-oriented languages . About private properties and private methods . There are the following points :
1. Usually we agree , Attributes starting with two underscores are private (private). Others are public (public).
2. Class can access private properties ( Method )
3. Private properties cannot be accessed directly outside the class ( Method )
4. Class can be passed ” Class name _ Private property ( Method ) name " Access private properties ( Method )
# Test private properties 、 Private method
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 You can change the calling mode of a method into “ Calling a ”. Don't write after the method name (), Next Face is a simple example :
# test @property Usage of
class Employee:
@property
def salary(self):
print("salary")
return 10000
emp1 = Employee()
#emp1.salary()
print(emp1.salary)
Inheritance can make subclasses have the characteristics of their parents , Improved code reuse . It is an incremental evolution in design , When the original parent class design remains unchanged , New features can be added , Or improve existing algorithms .
Python Support for multiple inheritance , A subclass can inherit more than one parent class . The inherited syntax format is as follows :
class Subclass class name ( Parent class 1[, Parent class 2,.. ]):
The class body
If no parent class is specified in the class definition , The default parent class is object class . in other words , object Is the parent of all classes , It's defined in it - - Some default implementations common to all classes , such as : _ new_ ().
When you define subclasses , The constructor of the parent class must be called in its constructor . The call format is as follows :
Parent class name _ jinit__ (self, parameter list )
# Test the basic use of inheritance
class Person:
def __init__(self,name,age):
self.name = name
self.__age = age # Private property
def say_age(self):
print(" Age 18")
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
self.score = score
#Student-->Person-->object class
print(Student.mro())
s = Student("tony",18,100)
s.say_age()
print(s.name)
#print(s.age)
print(dir(s))
print(s._Person__age) # Call the private property of the parent class
Members inherit : The subclass inherits all members of the parent class except the constructor .
Method rewriting : Subclasses can redefine the methods in the parent class q This will override the methods of the parent class , Also known as “ rewrite ”
# 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
self.score = score
def say_introduce(self):
''' Override parent method '''
print(" Tell the teacher , My name is :{0}".format(self.name))
s =Student("tony",18,100)
s.say_age()
s.say_introduce()
dir() and mro()
Built in functions dir() , It allows us to easily see all the properties of the specified object
Through the method of class mro( Or class properties _ mro_ You can output the inheritance hierarchy of this class .
rewrite __str__() Method
object There is a - individual _ _str_ () Method , For return - - For “ Description of the object ”, Corresponds to the built-in function str() Often used for print0 Method , Help us view the information of the object .- str_ () Can be rewritten .
# Test rewrite object Of __str__()
class Person: # Default inheritance object class
def __init__(self,name,):
self.name = name
def __str__(self):
return "my name is :{0}".format(self.name)
p = Person("tony")
print(p)
Python Support for multiple inheritance , A subclass can have multiple “ Immediate parents ". such , You have “ Multiple parent classes ” Characteristics . But because of , This will be " The overall hierarchy of the class " It's very complicated , Avoid using .
super() Get the definition of the parent class
In a subclass , If you want to get the method of the parent class , We can go through super() To do it .super() Represents the definition of the parent class , Not a parent object .
Polymorphism means that the same method call will have different behaviors due to different objects .
polymorphic ( polymorphism ) It means that the same method call may have different behaviors due to different objects . Note the following about polymorphism 2 spot :
1. Polymorphism is the polymorphism of method , Property is not polymorphic .
2. The existence of polymorphism has 2 Necessary conditions : Inherit 、 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() # polymorphic A method call , Call different methods according to different objects
else:
print(" Can't eat ")
ManEat(Chinese())