程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Fundamentals of python (VI) - advanced object-oriented

編輯:Python

Catalog

  • Introduction to the three characteristics of object-oriented
  • Inherit
    • Grammar format
    • Inheritance and overriding of class members
    • View the inheritance hierarchy of the class
  • object The root class
    • dir() View object properties
    • str() Method rewrite
  • multiple inheritance
  • MRO()
  • super() Get the parent class definition
  • polymorphic
  • Special methods and overloaded operators
  • Special properties
  • Shallow and deep copies of objects
  • Combine
  • Design patterns _ Factory mode implementation
  • Design patterns _ Singleton mode implementation
  • Integrated use of factory mode and singleton mode

Introduction to the three characteristics of object-oriented

encapsulation ( hide ): Hide object properties and implementation details , Know to provide necessary methods for external .
Inherit : Let subclasses have parent characteristics , 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 .
polymorphic : A method call will have different behavior due to different objects .

Inherit

Inheritance is a very important means of code reuse , Existing classes , We call it “ Parent class or base class ”, New classes , We call it “ Subclass or derived class ”.

Grammar format

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 class , It defines 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 .init(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 print_name(self):
print(self.name)
class Student(Person):
def __init__(self, name, age, id):
Person.__init__(self, name, age)
self.id = id
stu = Student('sherry',24,'2017')
stu.print_name()
print(Student.mro()) # View the inheritance hierarchy of the class 
print(dir(stu)) # Print all methods and properties 
print(stu._Person__age) # Access to private properties inherited from the parent class 
Output :
sherry
[<class '__main__.Student'>, <class '__main__.Person'>, <class 'object'>]
['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'id', 'name', 'print_name']
24

Inheritance and overriding of class members

  1. Members inherit : The subclass inherits all members of the parent class except the constructor , Including method , attribute , Private method , Private property , Only private methods and properties cannot be accessed directly .
  2. Method rewriting : Subclasses can redefine the methods in the parent class , So you Methods that override the parent class , Also known as “ rewrite ”
# Rewrite the test of the parent method 
class Person():
def __init__(self, name, age):
self.name = name
self.__age = age # Private property 
def print_name(self):
print(self.name)
class Student(Person):
def __init__(self, name, age, id):
Person.__init__(self, name, age)
self.id = id
def print_name(self):
''' Overriding the method of the parent class '''
print('my name is ', self.name)
stu = Student('sherry',24,'2017')
stu.print_name()
Output :
my name is sherry

View the inheritance hierarchy of the class

Through the method of class mro() Or class properties __mro__ You can output this class Inheritance hierarchy .

class Person():
def __init__(self, name, age):
self.name = name
self.__age = age # Private property 
def print_name(self):
print(self.name)
class Student(Person):
def __init__(self, name, age, id):
Person.__init__(self, name, age)
self.id = id
def print_name(self):
''' Overriding the method of the parent class '''
print('my name is ', self.name)
# stu = Student('sherry',24,'2017')
print(Student.mro())
Output :
[<class '__main__.Student'>, <class '__main__.Person'>, <class 'object'>]

object The root class

object Class is the parent of all classes , So all classes have object Class properties and methods .

dir() View object properties

# Test the basic use of inheritance 
class Person():
def __init__(self, name, age):
self.name = name
self.__age = age # Private property 
def print_name(self):
print(self.name)
class Student(Person):
def __init__(self, name, age, id):
Person.__init__(self, name, age)
self.id = id
def print_name(self):
''' Overriding the method of the parent class '''
print('my name is ', self.name)
obj = object()
stu = Student('sherry',24,'2017')
print(dir(obj))
print(dir(stu))
Output :
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'id', 'name', 'print_name']

str() Method rewrite

object There is one __str__() Method , Used to return a for “ Description of the object ”, Corresponds to the built-in function str(). Often used for print() Method , Help us view the information of the object .str() Can be rewritten .

class Person():
def __init__(self, name, age):
self.name = name
self.__age = age # Private property 
def print_name(self):
print(self.name)
def __str__(self):
return 'name:{0} age:{1}'.format(self.name, self.__age)
p = Person('sherry', 24)
print(p)
Output :
name:sherry age:24

multiple inheritance

Python Support for multiple inheritance , A subclass can have multiple “ Immediate parents ”. such , You have “ Multiple fathers class ” Characteristics . But because of , This will be “ The overall hierarchy of the class ” It's very complicated , Avoid using .(java Multiple inheritance is not supported )

class A():
pass
class B():
pass
class C(A,B):
pass
print(C.mro())
Output :
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]

MRO()

Python Support for multiple inheritance , If the father Methods with the same name in the class , When the subclass does not specify the parent class name , The interpreter will “ From left to right ” Search in order .

# test mro Method parsing order 
class A():
def say(self):
print('aa')
class B():
def say(self):
print('bb')
class C(B,A):
pass
c = C()
c.say() # Choose which parent method with the same name to use according to the inheritance order 
print(C.mro())
Output :
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

super() Get the parent class definition

In a subclass , If you want to get the method of the parent class , We can go through super() To do it .super() Get the definition of the parent class ( Not the object that gets the parent class ).

# test super()
class A():
def say(self):
print('aa')
class B(A):
def say(self):
super().say() # Call the superclass method 
A.say(self) # Call the superclass method 
print('bb')
b = B()
b.say()
Output :
aa
aa
bb

polymorphic

polymorphic (polymorphism) Refer to 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!')
class Chinese(Man):
def eat(self):
print('eat with chopsticks')
class English(Man):
def eat(self):
print('eat with fork')
class Indian(Man):
def eat(self):
print('eat with hand')
def manEat(m):
if isinstance(m,Man):
m.eat()
else:
print('can not eat!')
manEat(Man())
manEat(Chinese())
manEat(English())
manEat(Indian())
Output :
eat!
eat with chopsticks
eat with fork
eat with hand

Special methods and overloaded operators

python The heavy operator is actually realized by calling the special method of the object .

a = 20
b = 30
print(a+b)
print(a.__add__(b))
Output :
50
50

Common special methods :

Each operator actually corresponds to the corresponding method :

# Test operator overload 
class Person():
def __init__(self, name):
self.name = name
def __add__(self, other):
if isinstance(other, Person):
return '{0}-{1}'.format(self.name, other.name)
def __mul__(self, other):
if isinstance(other, int):
return self.name * other
p1 = Person('Sherry')
p2 = Person('Lily')
print(p1 + p2)
print(p1*10)
Output :
Sherry-Lily
SherrySherrySherrySherrySherrySherrySherrySherrySherrySherry

Special properties

python Contains a lot of double underlined start and end attributes , These are special properties , Special usage . Common special properties are listed here :

# Test special properties 
class A():
def say(self):
print('aa')
class B():
def say(self):
print('bb')
class C(B,A):
def __init__(self,name):
super().__init__()
self.name = name
c = C('sherry')
print(c.__dict__) #c Object's property list 
print(c.__class__) #c The class of the object 
print(C.__bases__) #C Class base class 
print(C.__mro__) #C Class inheritance 
print(C.__subclasses__)#C Subclasses of classes 
Output :
{
'name': 'sherry'}
<class '__main__.C'>
(<class '__main__.B'>, <class '__main__.A'>)
(<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
<built-in method __subclasses__ of type object at 0x7fefdacc8dd0>

Shallow and deep copies of objects

  • Assignment of variables
    Just form two variables , It actually points to the same object .
  • Shallow copy Python
    Copies are generally shallow copies . When copying , The contents of sub objects contained in the object are not copied . therefore , Source object And the copy object will reference the same child object .
  • · Deep copy use
    Use copy Modular deepcopy function , Recursively copies the child objects contained in the object . Source and copy objects All child objects are also different .
# Test light and deep copies 
import copy
class MobilePhone():
def __init__(self, cpu, screen):
self.cpu = cpu
self.screen = screen
class CPU():
def caculate(self):
print('cpu:\t', self)
class Screen():
def show(self):
print('screen:\t',self)
m1 = MobilePhone(CPU(), Screen())
print(' Test assignment ----')
m0 = m1
print('m1:\t',m1)
m1.cpu.caculate()
m1.screen.show()
print('m0:\t',m0)
m0.cpu.caculate()
m0.screen.show()
print(' Test shallow replication ----')
m2 = copy.copy(m1)
print('m1:\t',m1)
m1.cpu.caculate()
m1.screen.show()
print('m2:\t',m2)
m2.cpu.caculate()
m2.screen.show()
print(' Test deep replication ----')
m3 = copy.deepcopy(m1)
print('m1:\t',m1)
m1.cpu.caculate()
m1.screen.show()
print('m3:\t',m3)
m3.cpu.caculate()
m3.screen.show()
Output :
Test assignment ----
m1: <__main__.MobilePhone object at 0x7f8b0d6ed190>
cpu: <__main__.CPU object at 0x7f8b0d6ed130>
screen: <__main__.Screen object at 0x7f8b0d6ed100>
m0: <__main__.MobilePhone object at 0x7f8b0d6ed190>
cpu: <__main__.CPU object at 0x7f8b0d6ed130>
screen: <__main__.Screen object at 0x7f8b0d6ed100>
Test shallow replication ----
m1: <__main__.MobilePhone object at 0x7f8b0d6ed190>
cpu: <__main__.CPU object at 0x7f8b0d6ed130>
screen: <__main__.Screen object at 0x7f8b0d6ed100>
m2: <__main__.MobilePhone object at 0x7f8b0d6a9940>
cpu: <__main__.CPU object at 0x7f8b0d6ed130>
screen: <__main__.Screen object at 0x7f8b0d6ed100>
Test deep replication ----
m1: <__main__.MobilePhone object at 0x7f8b0d6ed190>
cpu: <__main__.CPU object at 0x7f8b0d6ed130>
screen: <__main__.Screen object at 0x7f8b0d6ed100>
m3: <__main__.MobilePhone object at 0x7f8b0d6ed280>
cpu: <__main__.CPU object at 0x7f8b0d6ede20>
screen: <__main__.Screen object at 0x7f8b0d6edd30>

Combine

“is-a” Relationship , We can use “ Inherit ”. So as to realize the methods and properties of the parent class owned by the child class .“is-a” Relationship refers to a relationship like this : Dogs are animals ,dog is animal. Dogs should inherit animals .
“has-a” Relationship , We can use “ Combine ”, You can also implement that one class has methods and properties of another class .” has-a” Relationship refers to such a relationship : Cell phones have CPU. MobilePhone has a CPU.

Design patterns _ Factory mode implementation

Design pattern is a special content of object-oriented language , It is our fixed practice when facing a certain kind of problem , Design There are many patterns , What's more popular is :GOF(Goup Of Four)23 Design patterns . Of course , We don't have it Need to learn all , Just learn a few common .
For starters , Let's learn the two most common patterns : Factory mode and singleton mode .
The factory pattern separates the creator from the caller , Using a specialized factory class will select the implementation class 、 Create objects Conduct unified management and control .

# Test factory mode 
class CarFactory():
def creatCar(self, brand):
if brand == ' Mercedes ':
return Benz()
elif brand == ' BMW ':
return BMW()
elif brand == ' BYD ':
return BYD()
else:
print('can not create!')
class Benz():
pass
class BMW():
pass
class BYD():
pass
factory = CarFactory()
c1 = factory.creatCar(' Mercedes ')
c2 = factory.creatCar(' BMW ')
c3 = factory.creatCar(' BYD ')

Design patterns _ Singleton mode implementation

The singleton pattern (Singleton Pattern) The central role of the government is Ensure that a class has only one instance , And provide a global access point to access the instance .
Singleton mode generates only one instance object , Reduce the overhead of system resources . When an object is generated, it needs to compare More resources , Such as Read configuration file 、 When other dependent objects are generated , Can produce a “ Singleton object ”, And then forever Resident in memory , Thus greatly reducing the overhead .

# Test singleton mode 
class MySingleton():
__obj = None
__init_flag = True
def __new__(cls, *args, **kwargs):
if cls.__obj == None:
cls.__obj = object.__new__(cls) # __obj Object is created only once obj Object is Mysingleton object 
return cls.__obj
def __init__(self, name):
if self.__init_flag == True:
print('init....')
self.name = name
self.__init_flag = False
a = MySingleton('aa')
b = MySingleton('bb')
c = MySingleton('cc')
print(a)
print(a.name)
print(b)
print(b.name)
print(c)
print(c.name)
Output :
init....
<__main__.MySingleton object at 0x7fce0f6e8130>
aa
<__main__.MySingleton object at 0x7fce0f6e8130>
aa
<__main__.MySingleton object at 0x7fce0f6e8130>
aa

Integrated use of factory mode and singleton mode

# Test the mixed use of factory mode and singleton mode 
class CarFactory():
__obj = None
__init_flag = True
def __new__(cls, *args, **kwargs):
if cls.__obj == None:
cls.__obj = object.__new__(cls)
return cls.__obj
def __init__(self):
if self.__init_flag:
print('init factory')
self.__init_flag = False
def creatCar(self, brand):
if brand == ' Mercedes ':
return Benz()
elif brand == ' BMW ':
return BMW()
elif brand == ' BYD ':
return BYD()
else:
print('can not create!')
class Benz():
pass
class BMW():
pass
class BYD():
pass
factory = CarFactory()
c1 = factory.creatCar(' Mercedes ')
c2 = factory.creatCar(' BMW ')
c3 = factory.creatCar(' BYD ')
factory2 = CarFactory()
print(factory)
print(factory2)
Output :
init factory
<__main__.CarFactory object at 0x7fd286eecc10>
<__main__.CarFactory object at 0x7fd286eecc10>

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved