Encapsulation, polymorphism, constrained class, Super () insight

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 writing..... a ⼀ functions. then this may also be referred to as encapsulation. thought to the subject. ⼀ is to these seemingly ⽆ crucial to the combination of content from system ⾯ ⼀ ⼀ 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 father's East ⻄ but ⼀ given to recognize one thing must be clear ⼀ have a 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 be accessed using inherit it? when a simple two classes have the same function or feature from the point of view of code ⾯ layer may be recorded using the inherited form. ⽗ extraction ⼀ a class, the class ⽗ prepared by the same portions of the two classes. then two class inherit this class were taken on it. the benefits of this writing is to avoid a lot of duplicate functions and write the code. If you go from a semantic analysis of the case. would be much simpler if the context is ⼀ species emerged x y. this when, y is ⼀ kind of generalization of the concept. x is more specific than y. then that x is y kind of submenus, such as cat is ⼀ animal cat inherited animal animals active. cats are also active. at this cat when the animals have created "action" this is a . Another example, is a fine white bone ⼀ a monster. Monsters day ⽣ there ⼀ relatively poor function called "Face to eat," White fine bone ⼀ out ⽣ know how to "eat the Face." At this point the white fine bone inheritance goblin.

3. polymorphism: On the same ⼀ objects, various forms of this in python is actually very easy to explain White's ⼀ variables such as creating a = 10, a is an integer type at this time but can make a program... = "abc", In this case, a separate warranty into a string type. this is polymorphism. ⼀ same variable may 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

self is a formal parameter, when executed obj1 = Foo ( 'a', 18), self equal OBJ1, when executed obj2 = Foo ( 'b', 78), self equal obj2, therefore, the content actually being encapsulated object obj1 and obj2, each object has a name and age properties, similar to the figure in the memory to store.

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

Obj1 and obj2 objects 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('a', 18)
print obj1.name    # 直接调用obj1对象的name属性printobj1.age     # 直接调用obj1对象的age属性

obj2 =Foo('b', 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('a', 18)
obj1.detail()  # Python默认会将obj1传给self参数,即:obj1.detail(obj1),所以,此时方法内部的 self = obj1,即:self.name 是a ;self.age 是 18
obj2 = Foo('b', 73)
obj2.detail()  # Python默认会将obj2传给self参数,即:obj1.detail(obj2),所以,此时方法内部的 self = obj2,即:self.name 是 b ; self.age 是 73

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.
In java or c # define variables or values must be passed to the function defined data type, otherwise an error.
FUNC DEF (A int):
Print ( 'A must be a number')
and is similar to the definition of such weak python language class, a may be in any form (str, int, object, etc.).
FUNC DEF (A):
Print ( 'A What can')

Another example:
class Fl:
Pass
class Sl (Fl):

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

class S2(F1):

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

Since Java or C #, when defining the function argument type must specify the parameters of the
order for Func function can either execute the show method S1 object, they can perform the show method S2 object, therefore, it defines a S1 and S2 class of the parent class
the actual parameters are passed: S1 and S2 objects Object
DEF Func (F1 obj):
"" "Func function will receive a type or type F1 F1 subclass" ""

print obj.show()

S1 = s1_obj ()
Func (s1_obj) # s1_obj S1 incoming object class in the function Func is performed show method S1 results: S1.show

S2 = s2_obj ()
Func (s2_obj) Method # incoming objects ss_obj Ss show class, Ss performed in the function Func results: S2.show
polymorphism Python pseudocode Java or C #
python in a proverb says well, you look like a duck, then you are a duck.
For explanation of the code is very short answer:
class A:
DEF F1 (Self):
Print ( 'A in 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()

B = obj2 ()
obj2.f1 ()
obj2.f2 ()
A B no coupling two classes, but in the sense that they are a standard and uniform.
The same function set with the same name, which facilitate the development of these two methods can become mutually duck typing.
Examples abound: str tuple list has index method, which is to unify the norm.
str bytes, etc. This is called cross-duck type.

III. Class constraints

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)

The results Chun 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 will 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 use this time to the constraints of the class, the class constraints, there are two:

\ 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! ! !
A class:
DEF F1 (Self):
Print ( 'A in F1')

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

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

obj = Foo()
obj.f1()

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'>]

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/sundawei7/p/11316187.html
Recommended