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
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
############################################
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 errorclass 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()
############################################
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
############################################
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)
############################################
# 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
############################################
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
############################################
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'>
>>>
############################################
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
############################################
############################################
# 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
############################################
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")
############################################
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)
############################################
@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)
############################################
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)
############################################
############################################
############################################
############################################
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
############################################
# 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
############################################
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
class A:
def __del__(self):
print("this is A.del")
a1 = A()
del a1
print("xxxxxx")
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)
############################################
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"]
############################################
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)