[英]Subclassing a Python class to inherit attributes of super class
我正在尝试从超类继承属性,但它们未正确初始化:
class Thing(object):
def __init__(self):
self.attribute1 = "attribute1"
class OtherThing(Thing):
def __init__(self):
super(Thing, self).__init__()
print self.attribute1
这会引发错误,因为即使Thing.attribute1存在,attribute1也不是OtherThing的属性。 我认为这是继承和扩展超类的正确方法。 难道我做错了什么? 我不想创建Thing的实例并使用其属性,为了简单起见,我需要它来继承它。
Python3使这变得容易:
#!/usr/local/cpython-3.3/bin/python
class Thing(object):
def __init__(self):
self.attribute1 = "attribute1"
class OtherThing(Thing):
def __init__(self):
#super(Thing, self).__init__()
super().__init__()
print(self.attribute1)
def main():
otherthing = OtherThing()
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.