Python object-oriented (inheritance, polymorphism, encapsulation, parameter passing, duck type, local variables)

Python object-oriented:

1. The attributes of the class can be dynamically added by instantiating the object

2. Ways to pass parameters:
1) The so-called model is abstract

2) Object = class name ()

3) Process:
(1) Class name (): first create an object, create a self variable
(2) call the init method, the parameters in the brackets of the class name will be received here
(3) execute the init method
(4) Return self object, self is a special big dictionary

# __init__,调用,执行
class A:
    count = 0
    def __init__(self):
        A.count += 1
f1 = A()
f2 = A()
print(f1.count)  # 2
print(f2.count)  # 2
class A:
	def __init__(self, a):
		self.a = a

	def func(self):
		print(self.a)
		print(self.b)
		print(self.c)

a = A(2)
a.b = 44  # 可以给实例化对象动态添加类的属性
a.c = 55
a.func()  # 2  44  55
print(a.__dict__)  # {'a': 2, 'b': 44, 'c': 55}  查看实例化对象的所有属性
print(A.__dict__)  # {'__module__': '__main__', '__init__' ... ...} 查看类的所有方法

3. For local variables in the class, the modification of the variable data type is shared, and the modification of the immutable data type is limited to the instantiated object

class A:
	name = ['wang']  # 可变数据类型
	age = 22         # 不可变数据类型
	def __init__(self, *args):  # args : ()
		self.a = args[0]

	def func(self):
		# 类的局部变量,函数内可以这样调用
		print(A.name, A.age)  # ['wang']  22
		print(self.a)
		print(self.b)
		print(self.c)
print('-----', A.name)  # ----- ['wang']
a = A(2)
a.b = 44  # 可以给实例化对象动态添加类的属性
a.c = 55
a.func()  # 2  44  55
a.name[0] = 'liu'  # 修改类中的变量
a.age = 18
# 可变数据类型修改是共享的(类和实例化对象共享),不可变数据类型修改不共享,只在自己的实例化对象有效
print(a.name, a.age)      # ['liu']  18
print(A.name, A.age)      # ['liu']  22
print(a.__dict__)  # {'a': 2, 'b': 44, 'c': 55, 'age': 18}  查看实例化对象的所有属性
# 查看类的所有方法和属性
print(A.__dict__)  # {'__module__': '__main__', 'name': ['liu'], 'age': 22, '__init__' ...}

Local variables in the class can be accessed by the class name

class A:
	name = ['wang']  # 可变数据类型
	age = 22         # 不可变数据类型
	def __init__(self, *args):  # args : ()
		self.a = args[0]

	def func(self):
		# 类的局部变量,函数内可以这样调用
		print(A.name, A.age)  # ['wang']  22
		print(self.a)
		print(self.b)
		print(self.c)
print('-----', A.name)  # ----- ['wang']

4. The definition of a class does not have to be __init__

5. Three characteristics of object-oriented: inheritance, polymorphism, encapsulation

6. Combination: The attribute value of an object is the object of another class, and the instantiated object of the class can be used as the attribute of the class

7. Class inheritance:

# 一个类可以被多个子类继承
# 一个类也可以继承多个父类
class A:pass #父类,基类,超类
class B:pass #父类,基类,超类
class A_son(A,B):pass#子类,派生类
print(A_son.__bases__)  # (<class '__main__.A'>, <class '__main__.B'>)
print(A.__bases__)      # (<class 'object'>,) 默认继承隐藏超类object

Multiple inheritance : a class inherits multiple parent class paths: A -> B -> C

# 多继承
class A:
    def func(self):print('A')
class B:
    def func(self):print('B')
class C:
    def func(self): print('C')
class D(A,B,C):
    pass
d = D()
d.func() #离的最近的func方法,应该是A的

Diamond inheritance : the two inherited classes inherit the same class

# 钻石继承 : 被继承的两个类继承同一个类
class A:
    def func(self):print('A')
class B(A):
    def func(self):print('B')
class C(A):
    def func(self): print('C')
class D(B,C):
    pass
# 继承路径 D -> B -> C -> A
d = D()
d.func() #离的最近的func方法,因该是B的,若B中没有func该找C的若B,C中都没有,该找A的

Funnel inheritance : the two inherited classes inherit different classes

class A:
    def func(self):print('A')
class E:
    def func(self):print('E')
class B(A):
    def func(self):print('B')
class C(E):
    def func(self): print('C')
class D(B,C):
    pass
print(D.mro())  #可记录继承路径 D -> B -> A -> C -> E
d = D()
d.func() #离的最近的func方法,应该是B的,若B中没有func,该找A的,若A中也都没有该找C的

(1) Classic class depth first python2.7 new-style classic coexistence, new-style class should inherit object
(2) new-style class breadth first python3.7 only has new-style class, default inheritance object, mro, super method is only available in new-style class, super only There is
(3) the essence of super in python3.7 : not directly looking for the parent class, but according to the breadth priority order of the caller’s node position

Diamond inheritance:
Insert picture description here

# 菱形继承:继承的两个类分别继承不同的类,不同的类又继承同一个类
# 类的先后顺序不可以交换
class F:
    def func(self): print('F')
class A(F):
    def func(self):print('A')
class B(A):
    def func(self):print('B')
class E(F):
    def func(self): print('E')
class C(E):
    def func(self):print('C')
class D(B,C):
    pass
print(D.mro())  #可记录继承路径 D -> B -> A -> C -> E -> F
d = D()
d.func() #离的最近的func方法,应该是B的,若B中没有func,找A的,A没找C,C没找E,都没找F

Interface class and abstract class:

1. Abstract class specification In
general, the functions that can be achieved by single inheritance are the same, so there can be some simple foundations in the parent class to implement
multiple inheritance situations. Because the functions are more complex, it is not easy to abstract the same functions. The specific implementation is written in the parent class

2. Abstract class or interface class: object-oriented development specification
(1) There is no interface class in python: there is the concept of interface interface in java
(2) Python comes with multiple inheritance, so we directly use class to implement the interface class
( 3) Support for abstract classes in python: In general, single inheritance cannot be instantiated
(4) Polymorphism Python inherently supports polymorphism (dynamic strongly typed language)

3. Duck type
(1) Don’t respect the similarity based on inheritance.
(2) I just need to implement my own code.
(3) If the two classes are just similar, the sibling relationship between the parent class’s subclasses will not occur. It’s the duck type. For
example: tuple list. This kind of similarity is constrained when writing code by yourself, rather than constrained by the parent class.
(4) Advantages: loose coupling has no effect between each similar class

Interface class :
Python does not support, the default is multiple inheritance, all methods must not be implemented

# 接口类
from abc import abstractmethod,ABCMeta
class Payment(metaclass=ABCMeta):     # 元类 默认的元类 type
    @abstractmethod
    def pay(self):
        raise NotImplemented          # 没有实现这个方法

class Wechat:
    def pay(self, money):
        print('微信支付了%s元'%money)
class Alipay:
    def pay(self, money):
        print('支付宝支付了%s元'%money)
class Applepay:
    def fuqian(self, money):        # 这个类没有pay这个方法
        print('Applepay支付了%s元'%money)

def pay_for(pay_obj, money):        # 统一支付入口
    pay_obj.pay(money)

wechat = Wechat()
ali = Alipay()
apple_pay = Applepay()
pay_for(wechat, 200)     # 微信支付了200元
pay_for(ali, 300)        # 支付宝支付了300元
# pay_for(apple_pay, 100)  # 报错 'Applepay' object has no attribute 'pay'

Abstract class:
Python support, does not support multiple inheritance

from abc import abstractmethod,ABCMeta
class Swim_Animal(metaclass=ABCMeta):
    @abstractmethod
    def swim(self):
        pass
swim_animal = Swim_Animal()
class Walk_Animal(metaclass=ABCMeta):
    @abstractmethod
    def walk(self):
        pass
walk_wnimal = Walk_Animal()
class Fly_Animal(metaclass=ABCMeta):
    @abstractmethod
    def fly(self):
        pass
fly_animal = Fly_Animal()

class Tiger(Walk_Animal,Swim_Animal):
    def walk(self):
    	pass
    def swim(self):
        pass
class Swan(Walk_Animal,Fly_Animal,Swim_Animal):pass

tiger = Tiger()
tiger.walk()

Static method:
In a fully object-oriented program, if a function has nothing to do with the object or the class, then use staticmethod to turn this function into a static method

class Login:
    def __init__(self,name,password):
        self.name = name
        self.pwd  = password
    def login(self):
        pass
    @staticmethod
    def get_usr_pwd():   #没有默认参数,就像函数一样
        usr = input('用户名:')
        pwd = input('密码:')
        Login(usr,pwd)
Login.get_usr_pwd()

Encapsulation:
1. Object-oriented encapsulation in a broad sense: code protection, object-oriented thinking itself is a kind of encapsulation
2. Only your own objects can call methods of their own classes
3. Encapsulation in a narrow sense – three object-oriented features
4 , Attributes and methods are hidden from you

Testcase:
1. The output of the following code is: # 20, 10, None

a = 10
b = 20
def func(a, b):
	print(a, b)
c = func(b, a)
print(c)  # 20, 10, None 无返回值return

2. Find the sum of the numbers in the string:

# 正则匹配求和  + 1-n次  ? 0-1次  * 0-n次
# 方法一
import re
s='123.33sdhf3424.34fdg323.324asda123'
p = r'\d+\.?\d*'
r = re.findall(p, s)   # ['123.33', '3424.34', '323.324', '123']
print(sum([float(i) for i in r]))  # 3993.994
# 方法二
import re
s='123.33sdhf3424.34fdg323.324asda123'
p = r'\d+\.?\d*'
r = re.findall(p, s)
r = '+'.join(r)
print(r)        # '123.33+3424.34+323.324+123'
print(eval(r))  # 3993.994  eval()函数求值

3. The output value is the key of the list type to form a list:

# 输出字典中值为list的key
d={'k1':'v1','k2':[1,2,3],('k','3'):{1,2,3}}
ret = [k for k in d if type(d[k]) is list]
print(ret)

4. Matching method

# strings字符串的筛选
# http开头的https开头的
# IP地址
import re
# if self.strings[k][1]
# 要不要匹配HTTP和HTTPS的,是开头match匹配还是全部search匹配
s = 'http://www.baidu.com'
s1 = 'https://www.163.com'
s3 = '/.,[,;],;ahm,ldshs'
# 从头开始匹配,开头为https和http
if re.match(r"http|https", s3):
	print(re.match(r"http|https", s3))
else:
	print('can not match')

# 匹配到是把IP提取出来,还是把原字符串存储下来
s2 = 'fsdf172.123.7.2sdfsg'
if re.findall(r'\d+\.\d+\.\d+\.\d+', s3):
	print(re.findall(r'\d+\.\d+\.\d+\.\d+', s3))
	print(re.findall(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', s3)) # 返回一个list
else:
	print('22222')

Guess you like

Origin blog.csdn.net/weixin_42563968/article/details/108548914