简体   繁体   English

用可选参数将python类子类化

[英]Subclassing a python class with optional arguments

I am new to Python. 我是Python的新手。 I have this code: 我有以下代码:

class SomeClass(OtherClass):
    name = "whatever"
    task = "nothing"

Now, I want to create a child class such that, I am able to instantiate it like this: 现在,我想创建一个子类,以便能够像这样实例化它:

child = ChildClass(task = "sometask")
child.name #=> "whatever"
child.task #=> "sometask"
child2 = ChildClass()
child2.task #=> "nothing"

How can I do that? 我怎样才能做到这一点?

First, you need to note that you are creating class variables in SomeClass , not instance variables 首先,需要注意,您正在SomeClass中创建类变量,而不是实例变量。

class SomeClass(object):
    def __init__(self, name = "whatever", task = "nothing"):
        self.name = name
        self.task = task

Now we have designed a class, which accepts two keyword arguments with default values. 现在,我们设计了一个类,该类接受两个带有默认值的关键字参数。 So, if you don't pass values to any of them, by default whatever will be assigned to name and nothing will be assigned to 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

You need to overwrite its initializer (sort of like a constructor in other languages): 您需要覆盖其初始化程序 (类似于其他语言的构造函数):

>>> 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM