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

Python object-oriented (2) class inheritance polymorphism classical and new classes static methods, class methods, instance methods underline in Python common magic methods

編輯:Python

Catalog

1. Class inheritance

1.1  Benefits of object orientation

 1.2  Example

1.3  super() Method

1.4    The relationship between class and instance

1.4.1  isinstance () function

1.4.2  Example : Judge the relationship between class and instance

2. polymorphic

2.1   Python The polymorphic

2.2  Python The polymorphic - Be careful

2.3   The benefits of polymorphism

3. Classic and new

3.1. python2 and python3 Different types of

3.2  Multiple inheritance of classes

3.2.1   Classes can be inherited multiple times

3.2.2  The order of inheritance between classic and new classes

3.2.3     The inheritance principle of classical and new classes

3.2.4  C3 Algorithm

 4. Static methods , Class method , Example method

4.1  Example method

4.2  Class method @classmethod

4.3  Static methods   @staticmethod

4.4  The difference between the various methods

5. python Underline in

5.1  Starting with a single underscore

5.1.1  In class

5.1.2  It's in the module

5.2  Starting with a double underscore

5.2.1  In class

5.2.2  It's in the module

5.3  Beginning and ending with a double underscore

6.python Common magic methods in

 Constructors (__new__/__init__)

 Destructor (__del__)

 Calling method (__call__)

 get data (__getitem__)

 Delete data (__delitem__)

 Set up the data (__setitem__)

 Other magic methods


1. Class inheritance

1.1  Benefits of object orientation

Benefits of object orientation One of the main benefits of object-oriented programming is code reuse , One way to achieve this reuse is through Inherit Mechanism .

 

Inheritance can be understood completely as Types and subtypes Relationship . • Can save a lot of code , No need to write , Use it directly • Derive different subclasses , Most of the code is the same , Part of the code is different

 

############################################ 

 1.2  Example

 Class inheritance • Code : Parent class Parent/ Subclass Child • Subclasses have __ini__: Execute your own initialization function • Subclasses don't have __init__: The constructor of the parent class will be executed automatically when the subclass is instantiated
class Animal():
species = "animal"
count = 0
def __init__(self):
self.name = "animal"
Animal.count += 1
print(" initialization animal...")
def breath(self):
print("i can breath")
def eat(self):
print("i can eat")
class Person(Animal):
# Override the properties of the parent class species
species = "Person"
animal1 = Animal()
print(animal1.count)
# Initialize yourself without init, Will execute the parent class __init__
p = Person()
print(p.species, p.count)

 print(p.name)

Person Class does not __init__, So the parent class is called Animal Of __init__ because Animal Of __init__ Yes name attribute , So there's no mistake print(d.name) and Dog Class has its own __init__, No more calls to the parent class __init__ however Dog Class __init__ There's no name attribute , So there's an error
class Dog(Animal):
def __init__(self):
print("i am dog")
# Override parent class eat Method
def eat(self):
print("dog is eating...")
d = Dog()
# # person Class does not init, Will call the parent class init
# # Parent class init Yes name attribute , So there's no mistake
# print(p.name)
# # dog Class has its own init, No more calls to the parent class init
# # dog class init There's no name attribute , Will report a mistake
# print(d.name)
d.eat()

############################################ 

1.3  super() Method

If a subclass of __init__ Method wants to use the parent class's __init__ Properties in , It can be used at this time super() Method

however super() Methods are usually written at the beginning , Because if it's written later, the parent class __init__ Method may override the cover class

Some properties .

class Pig(Animal):
count = 0 # Override parent properties
def __init__(self):
# Calling the init
super().__init__()
# super().eat()
self.name = "pig"
Pig.count += 1
print(" initialization pig")
print('*' * 20)
pig1 = Pig()
print(pig1.count, animal1.count)
********************
initialization animal...
initialization pig
1 3

############################################ 

1.4    The relationship between class and instance

1.4.1  isinstance () function

isinstance() Function to determine whether an object is a known type , similar type().

isinstance() And type() difference :

type() A subclass is not considered a superclass type , Do not consider inheritance relationships .

isinstance() Think of a subclass as a superclass type , Consider inheritance relationships .

It is recommended if you want to determine whether two types are the same isinstance().

grammar

Here are isinstance() The grammar of the method :

isinstance(object, classinfo)

############################################ 

1.4.2  Example : Judge the relationship between class and instance

# The relationship between class and instance
print('*'*20)
print(isinstance(pig1, Pig), isinstance(pig1, Animal))
print(type(pig1))
a = str(10)
# The so-called factory function is essentially a class
# ’ABC‘.lower(), Is the class call lower Method
print(type(a), str.lower("ABC"), "ABC".lower())
********************
True True
<class '__main__.Pig'>
<class 'str'> abc abc

############################################ 

2. polymorphic

2.1   Python The polymorphic

• polymorphic (Polymorphism) It literally means “ Multiple states ”. In object-oriented languages , There are many different interfaces The implementation method is polymorphic . • Python It's a polymorphic language , Advocating duck type . • In programming , Duck type is a style of dynamic type . • Duck model means :" When you see a bird walk like a duck 、 Swimming like a duck 、 It also sounds like a duck , So this bird is It can be called a duck ." • We don't care about the type of object , Is it a duck , Only care about behavior
class zhifubao():
def pay(self):
print("this is zhifubao pay")
class weixin():
def pay(self):
print("this is weixin pay")
class bank():
def pay(self):
print("this is bank pay")
z = zhifubao()
w = weixin()
b = bank()
def pay(obj): # Various forms of interfaces , Interface reuse
obj.pay()
pay(z)
pay(w)
pay(b)
E:\python\python3.9.1\python.exe E:/tlbb/2022-05-28-python object-oriented /05. polymorphic .py
this is zhifubao pay
this is weixin pay
this is bank pay
Process finished with exit code 0

############################################ 

2.2  Python The polymorphic - Be careful

• Polymorphism is based on inheriting and overriding parent class methods • Polymorphism is the technique of calling methods , It will not affect the internal design of the class ############################################ 

2.3   The benefits of polymorphism

• Increased program flexibility • Maintaining the status quo , No matter how diverse the objects are , Users are all in the same form to call , Such as func(animal) • Increased program scalability • By inheritance animal Class creates a new class , Users do not need to change their own code , Or use it func(animal) To call • polymorphic : The various forms of the same thing , Animals are divided into human beings , Pigs ( In defining the angle ) • polymorphism : A way of calling , Different execution effects ( polymorphism ) • Implement interface reuse ############################################ 

3. Classic and new

3.1. python2 and python3 Different types of

python2 There is only inheritance object Is the new class , The others are classic classes

python3 All classes are inherited by default object, therefore python3 It's all new


# Classic class adopt type All the instances viewed are instance
#       Classes and instances can only be passed through .__class__ attribute
# The new class adopt type The instance type viewed is the class name

<class '__main__.A'>
# __main__ Represents the current module
# Represents... Under the current module A class
[[email protected] lianxi]# python2
Python 2.7.5 (default, Oct 14 2020, 14:45:30)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A: pass
...
>>> a = A()
>>> type(a)
<type 'instance'>
>>> a.__class__
<class __main__.A at 0x7f2a02719258>
>>>
─────────────────────────────────────────────────────────────────
[[email protected] ~]# python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A: pass
...
>>> a = A()
>>> type(a)
<class '__main__.A'>
>>> a.__class__
<class '__main__.A'>
>>>

############################################ 

3.2  Multiple inheritance of classes

3.2.1   Classes can be inherited multiple times

• Defining classes A • Defining classes B,C Inherited from A • Defining classes D, Inherited from D • Defining classes E, Inherited from E • Defining classes F, Inherited from F

 

class A():
def test(self):
print("from A")
class B(A):
def test(self):
print("from B")
class C(A):
def test(self):
print("from C")
class D(B):
def test(self):
print("from D")
class E(C):
def test(self):
print("from E")
class F(D, E):
def test(self):
print("from F")
f = F()
f.test()

Classic class : F--D--B--A--E--C

The new class : F--D--B--E--C--A

############################################ 

3.2.2  The order of inheritance between classic and new classes

• Python If you inherit more than one class , So there are two ways to find out , Namely : Depth first and breadth-first

 ############################################ 

3.2.3     The inheritance principle of classical and new classes

• MRO(Method Resolution Order): Method parsing order • MRO Is in Python In multiple inheritance of class , Solution when defined Multiple methods with the same name / attribute when , To avoid ambiguity , Guarantee An algorithm implemented by the user to find the correct object . • For each class you define ,Python The accountant works out a method to analyze the order (MRO) list , This MRO A list is a A simple linear list of all base classes • Python2.2 Previous versions : Classic class (classic class) Time • MRO The method to DFS( Depth-first search ( Child node order : From left to right )) • Python2.2 edition : The new class (new-style class) Be born , There are two kinds of MRO Methods • Classic class MRO by DFS( Depth-first search ( Child node order : From left to right )) • The new class MRO by BFS( Breadth first search ( Child node order : From left to right )) • Python2.3 To Python2.7: Classic class 、 New types of peaceful development • from Python2.3 Start a new class MRO In its place C3 Algorithm • Python3 Until now : The new type unifies the Jianghu • Python3 From the beginning There are only new classes 了 , Adopted MRO It's still C3 Algorithm ############################################ 

3.2.4  C3 Algorithm

# c3 Algorithm
# First, add your own class to this sequence , Then judge the elements of the inherited sequence in turn
# If an element is not in another sequence or if it is first of the all inherited sequences , Then extract this element into this sequence 

############################################  

 4. Static methods , Class method , Example method

class A:
name = "class A"
def __init__(self): # Automatically call
self.country = "china"
# Example method , The first parameter represents the instance itself
def normal_method(self, name):
# Inside the method , That is, you can access class properties , You can also access instance properties
print("normal:")
print(self.name, name)
# Class method cls Representative class
@classmethod # Decorator Methods decorated with decorators are called class methods
def class_method(cls, name):
# Class methods can class attributes
print("classmethod")
print(cls, cls.name)
@staticmethod # Static methods
def static_method(name):
# Static methods can access class properties through class names
print("static_method", name, A.name)
a1 = A()
# Static methods , Example method , Class methods can be called through instances
a1.normal_method("a1")
a1.class_method("a1")
a1.static_method("a1")
# You can also call... Through classes
# Class needs to pass in instance parameters to call instance methods
A.normal_method(a1, "A")
A.class_method("A")
A.static_method("A")

############################################  

4.1  Example method

Example method , The first parameter represents the instance itself

Class attributes can be accessed in the instance method , You can also access instance properties

Can pass self Access instance properties
 # Example method , The first parameter represents the instance itself
def normal_method(self, name):
# Inside the method , That is, you can access class properties , You can also access instance properties
print("normal:")
print(self.name, name)

############################################  

4.2  Class method @classmethod

@classmethod  --> Decorator

Methods decorated with decorators are called class methods

Class methods can access class properties

Can pass cls Access class properties ( Use when you want to get a value that is not affected by the instance )
 # Class method cls Representative class
@classmethod # Decorator Methods decorated with decorators are called class methods
def class_method(cls, name):
# Class methods can class attributes
print("classmethod")
print(cls, cls.name)

############################################  

4.3  Static methods   @staticmethod

Static methods can access class properties through class names

 @staticmethod # Static methods
def static_method(name):
# Static methods can access class properties through class names
print("static_method", name, A.name)

############################################  

4.4  The difference between the various methods

 The difference between the various methods (@staticmethod、@classmethod) • Instance methods cannot be called by class name , But static methods and class methods can ( Do not instantiate access ) • Example method : Can pass self Access instance properties • Class method : Can pass cls Access class properties ( Use when you want to get a value that is not affected by the instance ) • Static methods : No access , By means of value transfer

############################################  

5. python Underline in

• An identifier is a name used to identify an object . • When naming identifiers , Certain rules need to be followed . The first character of an identifier must be a letter ( Case equal ), Or a downward stroke Line ("_"). • Identifiers that begin with underscores have a special meaning

############################################  

5.1  Starting with a single underscore

5.1.1  In class

This type of member variable is called Protect variables , This means that only class objects and subclass objects can access these variables themselves

5.1.2  It's in the module

If you write code “from < modular / Package name > import *”, So in order to “_” Neither the first module nor package will be exported Enter into , Unless... In a module or package “__all__” The list explicitly contains modules and packages . • It's kind of like practice , To make others ( Or yourself ) When you use this code, you will know With “_” The first name is for internal use only Use . just as Python Described in the documentation : The following line “_” Is the name of the prefix ( Such as _spam) It should be regarded as API Public in China and Africa part ( Whether it's a function 、 Methods are also data members ). here , Think of them as implementation details , There is no... When modifying them External notification is required .

############################################  

5.2  Starting with a double underscore

5.2.1  In class

• class : Only class objects can access , Even subclass objects can't access this data . Forced access to “ Object name ._ Class name __xxx“ The way

5.2.2  It's in the module

You cannot blur the import module   namely   Out-of-service “ from xxx import *“ Import package / modular .

• name ( It is a method name ) Front double underline (“__“) The use of is not a convention , For the interpreter, it has a specific The meaning of .Python This usage in is to avoid name conflicts with subclass definitions .Python The document states ,“__spam” This form ( At least two leading underscores , At most one subsequent underline ) Any identifier of will be “_classname__spam” This form replaces the original , ad locum “classname” Is the current class without leading underscores name .
class P:
"""
this is P
"""
_min = 1 # Protection properties
__max = 10 # Private property
def __init__(self):
self.name = "sc"
self.age = 4
self.__desc = "it"
def __make(self):
print(" This is a private method ")
print(self.__desc)
def _protectmake(self):
print(" It's a way to protect ")
def show(self):
print(self.__max, self.__desc)
class Child(P):
def show(self):
print(self.__max)
#
#
p = P()
c = Child()
# There is no difference between protected attributes and normal attributes
print(c._min, p._min, Child._min, P._min)
# Access private properties Subclasses cannot access private members
# print(c.__make)
# Class objects also cannot access private members
# print(p.__max)
# p.__make()
# Want to visit __make() Add the class name p._P__make()
# Private members can only be accessed inside a class
p.show()
print('*' * 20)
print(c._min)
# print(dir(p))
# '_P__desc', '_P__make', '_P__max',
# python The private property in is pseudo private , In fact, it is an identifier that begins with a double underscore
# Changed a name to store _ Class name __ identifier
E:\python\python3.9.1\python.exe E:/tlbb/2022-05-28-python object-oriented /08.python Underline in .py
1 1 1 1
10 it
********************
1
Process finished with exit code 0

############################################  

5.3  Beginning and ending with a double underscore

 Beginning and ending with double underscores ( __foo__ ) • representative Python Identification for special methods in . Actually , It's just a convention , Yes Python system , This will ensure that Conflict with user-defined name . • for example __init__() Constructor representing class . • Although you can also write your own special method names , However, it is not recommended that users use this naming method .__dict__ View namespace __class__ See which class the object belongs to __name__ View the name of the class __module__ Check which module you are in __doc__ Documentation Comments , class , function All document comments will be placed in __doc__ Inside
# Common special variables that begin and end with double underscores
# __dict__ # View namespace
print(P.__dict__)
print(p.__dict__)
print(P.__name__)
# __class__ See which class the object belongs to
print(p.__class__)
# __module__ Check which module you are in
print(P.__module__)
#
# __doc__ Documentation Comments , class , The function's documentation comments will be placed in __doc__ Inside
print(P.__doc__)
E:\python\python3.9.1\python.exe E:/tlbb/2022-05-28-python object-oriented /08.python Underline in .py
{'__module__': '__main__', '__doc__': '\n this is P\n ', '_min': 1, '_P__max': 10, '__init__': <function P.__init__ at 0x0000021A1689DC10>, '_P__make': <function P.__make at 0x0000021A168E1940>, '_protectmake': <function P._protectmake at 0x0000021A168E19D0>, 'show': <function P.show at 0x0000021A168E1A60>, '__dict__': <attribute '__dict__' of 'P' objects>, '__weakref__': <attribute '__weakref__' of 'P' objects>}
{'name': 'sc', 'age': 4, '_P__desc': 'it'}
P
<class '__main__.P'>
__main__
this is P
Process finished with exit code 0

############################################  

6.python Common magic methods in

Magic methods : It usually starts with a double underscore and ends with a double underscore

And it is a method with special meaning , Generally, there is no need to manually call

It will automatically execute in a specific scenario

 Constructors (__new__/__init__)

• __new__: Create examples • __init__: Initialize instance

 Destructor (__del__)

• Release... In the instance 、 It is automatically executed when destroying , Usually used to do some finishing work , Such as closing some database connections , close Open temporary files
class A:
def __del__(self):
print("this is A.del")
a1 = A()
del a1
print("xxxxxx")

 Calling method (__call__)

• When the instantiated object of the class is called as a function, it is automatically called
class A:
def __call__(self, name):
print(f"i am A.__call__,name is {name}")
a1 = A()
a1("sc")
def func1():
pass
print(dir(func1))

Custom exception classes

class NotIsIntException(Exception):
def __str__(self):
return 'NotIsIntException Type is not an integer '
n = input(' Please enter an integer ')
try:
if n.isdigit():
print(n)
else:
raise NotIsIntException
except NotIsIntException as ni:
print(ni)

############################################  

 get data (__getitem__)

• a[key] To access objects ,a[1:3] Call... When slicing __getitem__

 Delete data (__delitem__)

• del r[1] Called when the __delitem__ Method

 Set up the data (__setitem__)

• r['e']=213 Called when the __setitem__
class A:
def __init__(self):
self.data = {}
def __getitem__(self, key):
print("get data")
return self.data.get(key, 0)
def __setitem__(self, key, value):
print("set data:", key, value)
self.data[key] = value
def __delitem__(self, key):
print("delete data")
del(self.data[key])
a1 = A()
print(a1["key1"])
a1["key1"] = "xxxxxxx"
del a1["key1"]

############################################  

 Other magic methods

• __eq__(self, other) Defines the behavior of the equals sign , == • __ne__(self, other) Defines the behavior of inequality , != • __lt__(self, other) Defines the behavior of the less than sign , < • __gt__(self, other) Defines the behavior of the greater than or equal sign , >= • __add__(self, other) + operation • __mul__(self, other) * operation • __len__(self, other) Get the length Take addition for example :
class B:
def __init__(self, num):
self.num = num
def __add__(self, x):
print("this is add")
return self.num + x
a = B(4)
print(a + 6)


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