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

Python -- advanced object-oriented

編輯:Python

Three characteristics of object orientation : encapsulation 、 Inherit 、 polymorphic

Catalog

Inherit

Inheritance and overriding of class members

View the inheritance hierarchy of the class

object The root class

dir() View object properties

rewrite __str__() Method

multiple inheritance

MRO()

super() Get the parent class definition

polymorphic

Special methods and operator overloads

Special properties

Combine

Design patterns _ Factory mode implementation

Design patterns _ Singleton mode implementation


Inherit

         If a new class inherits from a designed class , It directly has the characteristics of existing classes , It greatly reduces the work difficulty . Existing classes , We call it “ Parent class or base class ”, New classes , We call it “ Subclass or derived class ”.

Grammar format

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 )

Inheritance and overriding of class members

1. Members inherit : The subclass inherits all members of the parent class except the constructor .

2. Method rewriting : Subclasses can redefine the methods in the parent class , This will override the methods of the parent class , Also known as “ rewrite ”

class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def say_age(self):
print(self.name," The age of :",self.age)
def say_name(self):
print(" My name is :",self.name)
class Student(Person):
def __init__(self,name,age,score):
self.score=score
Person.__init__(self,name,age)
def say_score(self): # Inherit
print(self.name," My score is ",self.score)
def say_name(self): # rewrite
print(" My name is :",self.name)
s1=Student("giaohu",18,100)
s1.say_name()
s1.say_age()
s1.say_score()
My name is : giaohu
giaohu The age of : 18
giaohu My score is 100

View the inheritance hierarchy of the class

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

class A:pass
class B(A):pass
class C(B):pass
print(C.mro())
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <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

rewrite __str__() Method

object There is one __str__() Method , Used to return a for “ Description of the object ”

class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return " The name is :{0}, Age is :{1}".format(self.name,self.age)
s1=Person("giaohu",18)
print(s1)
The name is :giaohu, Age is :18

multiple inheritance

         A subclass can have multiple “ Immediate parents ”. But because this will be “ The overall hierarchy of the class ” It's very complicated , So try to avoid using .

class A:
def aa(self):
print("aa")
class B:
def bb(self):
print("bb")
class C(B,A):
def cc(self):
print("cc")
c = C()
c.cc()
c.bb()
c.aa()
cc
bb
aa

MRO()

        MRO(Method Resolution Order): Method parsing order . We can go through mro() Methods to get “ Class hierarchy ”, The method parsing order is also according to this “ Class hierarchy ” Looking for . That is, if there is a method with the same name in the parent class , When the subclass does not specify the parent class name , The interpreter will “ From left to right ” Search in order .

class A:
def aa(self):
print("aa")
def say(self):
print("say AAA!")
class B:
def bb(self):
print("bb")
def say(self):
print("say BBB!")
class C(B,A):
def cc(self):
print("cc")
c = C()
print(C.mro()) # Print the hierarchy of classes
c.say()
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
say BBB!

super() Get the parent class definition

super() Represents the definition of the parent class , Not a parent object .

class Student(Person):
def __init__(self,name,age,score):
self.score=score
super().__init__(self,name,age)
#Person.__init__(self,name,age)

polymorphic

Polymorphism means that the same method call may have different behaviors due to different objects .

class Animal:
def shout(self):
print(" The animal gave a cry ")
class Dog(Animal):
def shout(self):
print(" puppy , Wang Wang Wang ")
class Cat(Animal):
def shout(self):
print(" kitten , cat ")
def animalShout(a):
if isinstance(a,Animal):
a.shout()
animalShout(Dog())
animalShout(Cat())
puppy , Wang Wang Wang
kitten , cat 

Special methods and operator overloads

The statistics of common special methods are as follows :

Each operator actually corresponds to the corresponding method , Statistics are as follows : 

 

  Special properties

These are special properties , Special usage .

Combine

“is-a” Relationship , We can use “ Inherit ”.

“has-a” Relationship , We can use “ Combine ”

class MobilePhone:
def __init__(self,cpu,screen):
self.cpu = cpu
self.screen = screen
class CPU:
def calculate(self):
print(" Calculation ")
class Screen:
def show(self):
print(" display frame ")
c = CPU()
s = Screen()
m = MobilePhone(c,s) # take CPU Classes and Screen Class composition MobilePhone class
m.cpu.calculate() # Same inheritance 

  Design patterns _ Factory mode implementation

         The factory pattern separates the creator from the caller , Using a specialized factory class will select the implementation class 、 Create an object into Unified management and control .

class CarFactory:
def createCar(self,brand):
if brand == " Mercedes ":
return Benz()
elif brand == " BMW ":
return BMW()
elif brand == ' BYD ':
return BYD()
else:
return " Unknown brand , could not be built "
class Benz:
pass
class BMW:
pass
class BYD:
pass
factory = CarFactory()
c1 = factory.createCar(" Mercedes ")
c2 = factory.createCar(" BMW ")
print(c1)
print(c2)

Design patterns _ Singleton mode implementation

         Singleton mode generates only one instance object , Reduce the overhead of system resources .


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