我正在将类提交扩展到SmsSubmission。但是,当我执行print x.sender
时,构造函数不会被初始化。我期待test sender
,但输出为None
。
这里有什么问题?
class Submission():
sender = None
def __init__(self):
self.sender = 'test sender'
class SmsSubmission(Submission):
message = None
def __init__(self):
self.message = 'test message'
x = SmsSubmission()
print x.sender
答案 0 :(得分:4)
您没有在子类中调用构造函数。您需要使用Submission.__init__()
或使用super()
明确调用它。
另请注意,当您使用Python 2时,您的基类应该继承自object
,以确保它是新式的类。
class Submission(object):
sender = None
def __init__(self):
self.sender = 'test sender'
class SmsSubmission(Submission):
message = None
def __init__(self):
Submission.__init__(self) # Calls the Submission constructor
# super(SmsSubmission, self).__init__()
self.message = 'test message'
x = SmsSubmission()
print x.sender