您的位置:首页 > 编程语言 > Python开发

Python 类的继承

2015-07-12 10:27 661 查看
有两个模块 file1.py 和 file2.py

file2中有个基类Base

def abc(self):
return "function-abc and name: " + self

class Base(object):
def __init__(self, name):
self.name = name

def run(self):
return abc(self.name)


file1中的Child类继承自 file2.Base

from file2 import Base

class Child(Base):
def __init__(self, name=None):
if not name:
name = 'T1-name'
super(Child, self).__init__(name)

def run(self):
return Base.run(self)

print Child().run()


结果:
function-abc and name: T1-name


即使file1中没有函数abc,因为导入的其他模块的类中关联了其他模块中的函数,在file1中是可以执行到的。

但是如果重写了子类的方法,并没有调用父类的,而是重新调用了其他模块的函数,那么便会导致找不到属性,因为file1模块中并没有定义函数abc()

class Child(Base):
def run(self):
# return Base.run(self)
return abc(self.name) # Error


#file2.Base
def abc(self):
return "function-abc and name: " + self

class Base(object):
def __init__(self, name):
self.name = name

def run(self):
# 下面两个是Child的类属性和实例属性,但是基类也能执行,
# 即使子类没有重写run方法,进行Base.run(self),基类也还是
# 能找到子类的属性。
print self.classattr
print self.inattr
return abc(self.name)

#file1.Child
from file2 import Base

class Child(Base):
classattr = 'Child class attr...'

def __init__(self, name=None):
self.inattr = "Child instance attr..."
if not name:
name = 'T1-name'
super(Child, self).__init__(name)

def run(self):
return Base.run(self)

print Child().run()
# Child class attr...
# Child instance attr...
# function-abc and name: T1-name


再来看一个例子:

# file1.Base
class Base(object):

classattr = 'Base class attr'

def __init__(self):
self.inattr = 'Base instance attr'
return self.handler()

def handler(self):
pass

def setup(self):
return "Base.setup method"

# file2.Child
from file1 import Base

class Child(Base):

classattr = 'Child class attr'

def __init__(self):
super(Child, self).__init__()
self.inattr = "Child instance attr"

def handler(self):
print self.inattr
print 'Child.handler method'
print self.setup()

def setup(self):
return "Child.setup method"

print Child()

结果:
Child instance attr
Child.handler method
Child.setup method
<__main__.Child object at 0x7fca2e946890>


子类中初始化了父类的init,所以执行了父类的init中的
return  self.handler()


而子类中重写了handler方法,所以执行了子类的handler方法。

因为子类初始化中的
self.inattr = "Child instance attr"
写在super之后,所以覆盖了父类的实例属性
self.inattr


子类中的handler最后执行了setup方法,setup被子类Child重写,如果子类中没有重写,那么便会去找父类中setup方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: