首页 > 技术文章 > python 面向对象

lianghong881018 2019-06-25 10:59 原文

多态(Polymorphism): 意味着可以对不同类的对象使用同样的操作

   

def getPrice(object):
    if isinstance(object, tuple):
        return object[1]
    elif isinstance(object, dict):
        return object['price']
    else:
        return magic_network_method(object)

  

def length_message(x):
    print("The length of", repr(x), 'is', len(x))

length_message('panzidong')
length_message([1,2,3,4])

result:

The length of 'panzidong' is 9
The length of [1, 2, 3, 4] is 4

 

封装(Encapsulation): 对外部隐藏对象的工作细节

     "百灵鸟类"是“鸟类”的子类(subclass), 鸟类是百灵鸟类的超类(superclass)

     不同的子类,在使用超类的方法时, 有可以会需要重写(override)父类的方法

     如fly,有些子类不会飞,就需要重写,如企鹅。

Person类:

__metaclass__ = type

class Person:
    def setName(self, name):
        self.name = name
    def getName(self):
        return self.name
    def greet(self):
        print("hello, world, i'a %s" % self.name)

# 如何让方法和特性变成私有

class Secretive:
    def __inaccessible(self):
        print('bet you can\'t see me...')

    def accessible(self):
        print("The secret message is:")
        self.__inaccessible()


s = Secretive()
s.accessible()

result:

The secret message is:
bet you can't see me...

 

继承(Inheritance): 以通用的类为基础建立专门的类对象

class Filter:
    def init(self):
        self.blocked = []
    def filter(self, sequence):
        return [x for x in sequence if x not in self.blocked]

class SPAMFilter(Filter):
    def init(self):
        self.blocked = ['SPAM']

print(issubclass(SPAMFilter, Filter))

   多个超类:

    

class Calculator:
    def calculate(self, expression):
        self.value = eval(expression)

class Talker:
    def talk(self):
        print("hi, my value is", self.value)

class TalkingCalculator(Calculator,Talker):
    pass

 note: 先继承的类中的方法会重写后续继续的类中的方法。

推荐阅读