The Object Oriented: three characteristics: Inheritance (already speaking), encapsulation, polymorphism

Preface:

python object-oriented three characteristics: inheritance, encapsulation, polymorphism.

1. Package: The package ⼀ lot of data to objects in the code package to ⼀ fixing function code blocks, functions, objects, modules which are packaged into packages belonging to a particular situation thought specific analysis such as you.... wrote very ⽜ B ⼀ function. this may also be referred to as that packaged in ⾯ to a subject thought. ⽆ is seemingly the more crucial ⼀ combination of content from the system to ⼀ ⼀ storing anything and Use. this is the package.

2. Inheritance: Submenu class can automatically have ⽗ like all other content in addition to private property, said White, and submenus can easily reach of children Use of East ⻄ father but my friends, ⼀ given to recognize one thing must be clear ⼀... first, father, after the reach of children submenus. order can not be chaotic, implementation inheritance in python is very simple. in a statement class, ⾯ add one hour for parentheses after the class name, you can complete inheritance. so what can use the when inherit it? simple. Both classes have the same functionality or features from the code level ⾯ point of view can be taken in the form of inherited Use extraction ⼀ a ⽗ class, this class ⽗ write the same part of the two classes. then two classes extend this class were taken on it. the benefits of this writing is that we can avoid a lot of duplication of functions and write the code. If you go from a semantic analysis of the case. would be much simpler if the context of the emergence of x is ⼀ kind y. in this case, y is ⼀ kind of generalization of the concept. x than y more specific. it is then x y kind of submenus, such as cat is ⼀ animal cat inherited animal animals active. cats are also active. then there is a cat in the creation of the animals "Action" this property. As another example, the white fine bone ⼀ is a monster. Monsters day ⽣ there ⼀ relatively poor function called "Face to eat," White fine bone ⼀ out ⽣ know how to "eat the Face." This when the white fine bone inherited monster.

3. polymorphism: On the same ⼀ objects, various forms of this in python is actually very easy to explain because we ⼀ white straight in Using just not specifically for example, we create ⼀ variables a = 10.... we know that at this time a is an integer type, but we can make the program a = "alex", this time, a separate warranty into a string type. this is what we all know. but I want to tell you that. this is polymorphism with ⼀ variables can be a variety of forms.

1. Packaging

Package, by definition is the contents of the package somewhere, go after the call content is encapsulated in somewhere.

Therefore, when using the object-oriented characteristics of the package, it is necessary:

  • Encapsulation of the content to somewhere
  • Call content is encapsulated from somewhere

The first step: The contents of the package to somewhere

img

img

Step two: Call package content from somewhere

When you call content is packaged, there are two cases:

  • Direct calls through the object
  • Indirect call through self

1, the content is encapsulated by the object calling directly

The figure shows an object obj1 obj2 and stored in memory mode, according to the stored content format may be so packaged call: Object attribute name

class FOO:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        
obj1 = Foo('lalala',18)
print(obj1.name) 
print(obj1.age)

obj2 = Foo('qwe',78)
print(obj2.name)
print(obj2.age)

2, an indirect call by self packaged content

Performing the methods of the class required an indirect call through the self packaged content

class FOO:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def detail(self):
        print(self.name)
        print(self.age)
obj1 = Foo('lalala',18)
obj1.detail()

obj2 = Foo('qwe',78)
obj2.detail()

In summary, for the object-oriented packages, in fact, it is to use a constructor encapsulation of the content object, and then packaged contents obtained indirectly or directly self through the object.

2. polymorphism

Polymorphism, the same object, a variety of forms. python default support multi-state

# python 一个变量可以指向多种数据
# a = [1,2,3]
# a = 'qweeqrq'
'''
java:
int a = 123

def func(int x):
    print(x)
    
    
python:
def func(x):
    print(x)
'''

Ducks type

python中有一句谚语说的好,你看起来像鸭子,那么你就是鸭子。
对于代码上的解释其实很简答:
class A:
    def f1(self):
        print('in A f1')
        
    def f2(self):
        print('in A f2')
        
class B:
    def f1(self):
        print('in B f1')
     
    def f2(self):
        print('in B f2')
           
obj1 = A()
obj1.f1()
obj1.f2()

obj2 = B()
obj2.f1()
obj2.f2()
# A 和 B两个类完全没有耦合性,但是在某种意义上他们却统一了一个标准。
# 对相同的功能设定了相同的名字,这样方便开发,这两个方法就可以互成为鸭子类型。

# 这样的例子比比皆是:str  tuple list 都有 index方法,这就是统一了规范。
# str bytes 等等 这就是互称为鸭子类型。

3. Constraints class

Therefore especially First, you have to know. Constraint is of the class.

Speak with an example:

The company Xiao Ming to make their website a complete payment function, Xiao Ming wrote two categories, as follows:

class QQpay:
    def pay(self,money):
        print('使用qq支付%s元' % money)

class Alipay:
    def pay(self,money):
        print('使用阿里支付%s元' % money)

a = Alipay()
a.pay(100)

b = QQpay()
b.pay(200)

But this place is not easy to write the above, it is unreasonable, the boss said to let him rectification, unified look at the manner of payment, Xiao Ming began finishing work overtime:

class QQpay:
    def pay(self,money):
        print('使用qq支付%s元' % money)

class Alipay:
    def pay(self,money):
        print('使用阿里支付%s元' % money)

def pay(obj,money):  # 这个函数就是统一支付规则,这个叫做: 归一化设计。
    obj.pay(money)

a = Alipay()
b = QQpay()

pay(a,100)
pay(b,200)

Wrote half of the interface, Xiao Ming has finally received a big project, the results of the company tasteless, recruited a wild programmer Chun took over Bob's work, the boss gave Chun scheduled task, so he wrote a micro-channel payment functions:

class QQpay:
    def pay(self,money):
        print('使用qq支付%s元' % money)

class Alipay:
    def pay(self,money):
        print('使用阿里支付%s元' % money)

class Wechatpay:  # 野生程序员一般不会看别人怎么写,自己才是最好,结果......
    def fuqian(self,money):
        print('使用微信支付%s元' % money)

def pay(obj,money):
    obj.pay(money)

a = Alipay()
b = QQpay()

pay(a,100)
pay(b,200)

c = Wechatpay()
c.fuqian(300)

Chun result, punishment, and rectification, then the spring of Columbia, worked hard to re-sort code:

class Payment:   """ 此类什么都不做,就是制定一个标准,谁继承我,必须定义我里面的方法。   """
    def pay(self,money):
        pass

class QQpay(Payment):
    def pay(self,money):
        print('使用qq支付%s元' % money)

class Alipay(Payment):
    def pay(self,money):
        print('使用阿里支付%s元' % money)

class Wechatpay(Payment):
    def fuqian(self,money):
        print('使用微信支付%s元' % money)

def pay(obj,money):
    obj.pay(money)

a = Alipay()
b = QQpay()

pay(a,100)
pay(b,200)

c = Wechatpay()
c.fuqian(300)

However, this will be a problem, if the programmer wild again, he does not see other methods of payment, do not know why you want to define a class that inherits a method does not make sense, so he would go its own way:

class Payment: 
  """ 此类什么都不做,就是制定一个标准,谁继承我,必须定义我里面的方法。
   """
    def pay(self,money):
        pass

class QQpay(Payment):
    def pay(self,money):
        print('使用qq支付%s元' % money)

class Alipay(Payment):
    def pay(self,money):
        print('使用阿里支付%s元' % money)

class Wechatpay(Payment):
    def fuqian(self,money):
        print('使用微信支付%s元' % money)

def pay(obj,money):
    obj.pay(money)

a = Alipay()
b = QQpay()

pay(a,100)
pay(b,200)

c = Wechatpay()
c.fuqian(300)

So this time we have to use the class constraints, constraints on class in two ways:

  1. Extraction ⽗ class and then defined the Remedies in ⽗ class. In this Remedies in nothing with a dry. ⼀ to throw exceptions on it. All submenus that such classes must override the Remedies. Otherwise Visit when it will error.

  2. Use metaclass described ⽗ class are given in ⼀ abstract Remedies metaclass. Such classes would have submenus give specific implementation of the abstract methods for the camera. Constraints may also play effect.

First with the first way to solve:

class Payment:
    """
    此类什么都不做,就是制定一个标准,谁继承我,必须定义我里面的方法。
    """
    def pay(self,money):
        raise Exception("你没有实现pay方法")

class QQpay(Payment):
    def pay(self,money):
        print('使用qq支付%s元' % money)

class Alipay(Payment):
    def pay(self,money):
        print('使用阿里支付%s元' % money)

class Wechatpay(Payment):
    def fuqian(self,money):
        print('使用微信支付%s元' % money)

def pay(obj,money):
    obj.pay(money)

a = Alipay()
b = QQpay()
c = Wechatpay()
pay(a,100)
pay(b,200)
pay(c,300)

The second way: to introduce the concept of an abstract class treatment.

from abc import ABCMeta,abstractmethod
class Payment(metaclass=ABCMeta):    # 抽象类 接口类  规范和约束  metaclass指定的是一个元类
    @abstractmethod
    def pay(self):pass  # 抽象方法

class Alipay(Payment):
    def pay(self,money):
        print('使用支付宝支付了%s元'%money)

class QQpay(Payment):
    def pay(self,money):
        print('使用qq支付了%s元'%money)

class Wechatpay(Payment):
    # def pay(self,money):
    #     print('使用微信支付了%s元'%money)
    def recharge(self):pass

def pay(a,money):
    a.pay(money)

a = Alipay()
a.pay(100)
pay(a,100)    # 归一化设计:不管是哪一个类的对象,都调用同一个函数去完成相似的功能
q = QQpay()
q.pay(100)
pay(q,100)
w = Wechatpay()
pay(w,100)   # 到用的时候才会报错

# 抽象类和接口类做的事情 :建立规范
# 制定一个类的metaclass是ABCMeta,
# 那么这个类就变成了一个抽象类(接口类)
# 这个类的主要功能就是建立一个规范

Summary: Constraints in fact ⽗ class for submenus class into ⾏ constraints submenus class must write xxx Remedies There are two constraints in python shutter mode and Remedies...:

1. Use abstract classes and abstract Remedies, since the source text is ⽅ java and c #. Using the frequency is so little

2. Using the Face to throw ⽅ unusual case. And try to throw a NotImplementError. This is more professional, more clear on it and wrong. (Recommended)

4. super () in-depth understanding

super strict accordance with the order of succession is the class! ! !

class A:
    def f1(self):
        print('in A f1')
    
    def f2(self):
        print('in A f2')


class Foo(A):
    def f1(self):
        super().f2()
        print('in A Foo')
        
        
obj = Foo()
obj.f1()

other methods may be a super class

class A:
    def f1(self):
        print('in A')

class Foo(A):
    def f1(self):
        super().f1()
        print('in Foo')

class Bar(A):
    def f1(self):
        print('in Bar')

class Info(Foo,Bar):
    def f1(self):
        super().f1()
        print('in Info f1')

obj = Info()
obj.f1()

'''
in Bar
in Foo
in Info f1
'''
print(Info.mro())  # [<class '__main__.Info'>, <class '__main__.Foo'>, <class '__main__.Bar'>, <class '__main__.A'>, <class 'object'>]

super () strictly in accordance with the order of class mro

class A:
    def f1(self):
        print('in A')

class Foo(A):
    def f1(self):
        super().f1()
        print('in Foo')

class Bar(A):
    def f1(self):
        print('in Bar')

class Info(Foo,Bar):
    def f1(self):
        super(Foo,self).f1()
        print('in Info f1')

obj = Info()
obj.f1()

Guess you like

Origin www.cnblogs.com/fengqiang626/p/11315684.html