继承

继承 #

基本使用 #

Python 使用 (父类) 表示继承关系。

class Button(View):

继承后可以通过 super() 调用父类的函数,如果当前类和父类的函数参数相同时可以省略参数列表。

如果重写父类方法时需要调用父类方法,需要使用 parentClass.method(self, ...) 的形式来调用。

class View:

    def __init__(self, width, height):
        self.width = width
        self.height = height

    def desc(self, prefix):
        return "{prefix} width = {width}, height = {height}" \
            .format(prefix=prefix, width=self.width, height=self.height)


class Button(View):
    def __init__(self, width, height, name):
        super().__init__(width, height)
        self.name = name

    # 特别注意调用父类方法的语法形式
    def desc(self, prefix):
        return View.desc(self, prefix) + " ,name = {name}".format(name=self.name)

如果父类初始化函数含有参数时,而子类覆盖了其初始化函数并且没有调用父类的初始化函数。此时如果试图调用那些会访问父类初始化函数中定义的变量时会报错。

class ViewGroup(View):
    def __init__(self):
        pass

view_group = ViewGroup()

此时可以通过调用父类的初始化函数为其进行初始化操作。

view_group = ViewGroup()
View.__init__(view_group, 0, 0)
print(view_group.desc(' => '))

多重继承 #

class RadioGroup(Button, ViewGroup):
    def __init__(self):
        super().__init__()
        self.index = 0

其它方法 #

print(issubclass(Button, View))  # True
print(issubclass(Button, Button))  # True
print(issubclass(Button, object))  # True

print(isinstance(button, View))  # True
print(isinstance(button, Button))  # True
print(isinstance(button, ViewGroup))  # False

print(hasattr(button, 'width'))  # True
print(getattr(button, 'not exist', 'default value'))  # default value
setattr(button, 'color', 'red')
print(getattr(button, 'color'))  # red
delattr(button, 'color')
沪ICP备17055033号-2