我是Python新手。我有这段代码:
class SomeClass(OtherClass):
name = "whatever"
task = "nothing"
现在,我想创建一个子类,我可以像这样实例化它:
child = ChildClass(task = "sometask")
child.name #=> "whatever"
child.task #=> "sometask"
child2 = ChildClass()
child2.task #=> "nothing"
我该怎么做?
答案 0 :(得分:3)
首先,您需要注意在SomeClass
创建类变量,而不是实例变量
class SomeClass(object):
def __init__(self, name = "whatever", task = "nothing"):
self.name = name
self.task = task
现在我们设计了一个类,它接受两个带默认值的关键字参数。因此,如果您未将值传递给其中任何一个,默认情况下whatever
将分配给name
,而nothing
将分配给task
。
class ChildClass(SomeClass):
def __init__(self, name = "whatever", task = "nothing"):
super(ChildClass, self).__init__(name, task)
child1 = ChildClass(task = "sometask")
print child1.name, child1.task
# whatever sometask
child2 = ChildClass()
print child2.name, child2.task
# whatever nothing
答案 1 :(得分:1)
您需要覆盖其初始值设定项(有点像其他语言的构造函数):
>>> class SomeClass:
... name='whatever'
... task='nothing'
...
>>> class ChildClass(SomeClass):
... def __init__(self, name=None, task=None):
... if name is not None:
... self.name = name
... if task is not None:
... self.task = task
...
>>> child = ChildClass(task='sometask')
>>> child.name
'whatever'
>>> child.task
'sometask'
>>> child2 = ChildClass()
>>> child2.task
'nothing'