Object-oriented: 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.

A package

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

It is a form of self parameter when executed obj1 = Foo ( 'wupeiqi', 18), self equal obj1

When performing obj2 = Foo ( 'alex', 78), self equal obj2

So, in fact, is encapsulated into the content object obj1 and obj2, each object has a name and age properties, similar to the figure in the memory to store.

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('wupeiqi', 18)
print obj1.name    # 直接调用obj1对象的name属性
print obj1.age     # 直接调用obj1对象的age属性
 
obj2 = Foo('alex', 73)
print obj2.name    # 直接调用obj2对象的name属性
print obj2.age     # 直接调用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('wupeiqi', 18)
obj1.detail()  # Python默认会将obj1传给self参数,即:obj1.detail(obj1),所以,此时方法内部的 self = obj1,即:self.name 是 wupeiqi ;self.age 是 18
  
obj2 = Foo('alex', 73)
obj2.detail()  # Python默认会将obj2传给self参数,即:obj1.detail(obj2),所以,此时方法内部的 self = obj2,即:self.name 是 alex ; self.age 是 78

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.

More than two states

Polymorphism, the same object, a variety of forms. The default python support polymorphism.

# 在java或者c#定义变量或者给函数传值必须定义数据类型,否则就报错。

def func(int a):
    print('a必须是数字')
    
# 而类似于python这种弱定义类语言,a可以是任意形态(str,int,object等等)。
def func(a):
    print('a是什么都可以')
    
# 再比如:
class F1:
    pass


class S1(F1):
    
    def show(self):
        print 'S1.show'


class S2(F1):
    
    def show(self):
        print 'S2.show'


# 由于在Java或C#中定义函数参数时,必须指定参数的类型
# 为了让Func函数既可以执行S1对象的show方法,又可以执行S2对象的show方法,所以,定义了一个S1和S2类的父类
# 而实际传入的参数是:S1对象和S2对象

def Func(F1 obj):
"""Func函数需要接收一个F1类型或者F1子类的类型"""

    print obj.show()
    

s1_obj = S1()
Func(s1_obj)  # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法,结果:S1.show

s2_obj = S2()
Func(s2_obj)  # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法,结果:S2.show

Python伪代码实现Java或C  # 的多态

Polymorphic Examples

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


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

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

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

Three types of constraints

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 and looked Bai teach you to learn python relevant information, the 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. time of the visit will give an 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)

Four. 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/changxin7/p/11309086.html