python派生类的构造函数

发布于 2024-12-15 17:54:24 字数 1033 浏览 3 评论 0原文

class baseClass():
  def __init__(self,mark,name):
    self.mark = mark
    self.name = name

class derivedClass(baseClass):

b1 = derivedClass(name='Jibin')
print b1.name

这是我最初的代码&效果很好。

(注意:我无权访问baseClass

但后来我不得不将一个额外的属性rank传递给衍生类。所以我编辑了像这样的代码。

class baseClass():
  def __init__(self,mark,name):
    self.mark = mark
    self.name = name

class derivedClass(baseClass):
  def __init__(self,rank):
    self.rank = rank 

b1 = derivedClass(name='Jibin')
print b1.name

这导致了错误 __init__() 获得了意外的关键字参数 'name'

这是预期的,因为 categories__init__ 没有参数 <代码>名称。

我不想在实际 baseClasscategories b'cos 的 __init__ 中添加额外的参数 name十个参数而不是 2(mark,name) &如果我将它们全部作为派生类的附加参数,我将弄乱其参数列表。

注意:我知道使用 baseClass.__init__(self)super(drivenClass, self).__init__() 初始化 baseClass

class baseClass():
  def __init__(self,mark,name):
    self.mark = mark
    self.name = name

class derivedClass(baseClass):

b1 = derivedClass(name='Jibin')
print b1.name

This was my code initially & it worked fine.

(Note: I don't have access to baseClass)

But later I had to pass a additional attribute rank to derivedClass.So I edited the code like this.

class baseClass():
  def __init__(self,mark,name):
    self.mark = mark
    self.name = name

class derivedClass(baseClass):
  def __init__(self,rank):
    self.rank = rank 

b1 = derivedClass(name='Jibin')
print b1.name

This caused an error __init__() got an unexpected keyword argument 'name'

This was expected as the __init__ of derivedClass do not have a argument name.

I don't want to add an additional argument name to __init__ of derivedClass b'cos in real baseClass has ten arguments instead of 2(mark,name) & if i give all them as additional argument to derivedClass I will be cluttering its argument list.

Note: I am aware of initializing baseClass using baseClass.__init__(self) or super(derivedClass, self).__init__()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

月朦胧 2024-12-22 17:54:24

也许你可以尝试这样的事情

class BaseClass(object):
  def __init__(self, mark=None, name=None):   # you're using named parameters, declare them as named one.
    self.mark = mark
    self.name = name

class DerivedClass(BaseClass):   # don't forget to declare inheritance
  def __init__(self, rank=None, *args, **kwargs):    # in args, kwargs, there will be all parameters you don't care, but needed for baseClass
    super(DerivedClass, self).__init__(*args, **kwargs)
    self.rank = rank 

b1 = DerivedClass(name='Jibin')
print b1.name

Maybe you can try something like this

class BaseClass(object):
  def __init__(self, mark=None, name=None):   # you're using named parameters, declare them as named one.
    self.mark = mark
    self.name = name

class DerivedClass(BaseClass):   # don't forget to declare inheritance
  def __init__(self, rank=None, *args, **kwargs):    # in args, kwargs, there will be all parameters you don't care, but needed for baseClass
    super(DerivedClass, self).__init__(*args, **kwargs)
    self.rank = rank 

b1 = DerivedClass(name='Jibin')
print b1.name
这个俗人 2024-12-22 17:54:24

此博客介绍了如何解决此类问题。解决方案是让 base 以及 衍生 在其 __init__ 中接受一个 **kwargs 参数并传递该参数到对 super 的调用。

This blog describes how to solve this sort of problem. The solution is to have base as well as derived accept a **kwargs argument in their __init__ and pass that to the call to super.

小女人ら 2024-12-22 17:54:24

衍生类实际上不是派生自baseClass。要在 python 中进行子类化,您必须向类定义提供父类,因此:

class DerivedClass(BaseClass):
    pass

DerivedClass 现在继承了 BaseClass 的方法,包括 __init__()。如果您不重写方法,则在子类上调用它实际上会调用超类上定义的方法。

所以,如果你想允许 DerivedClass(name='Jibin'),你需要提供一个专门的 init():

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

class DerivedClass(BaseClass):
    def __init__(self, mark, name, rank):
        BaseClass.__init__(self, mark, name)
        self.rank = rank

现在,你还想支持额外的关键字参数到 DerivedClass() 而无需显式添加它们。实现此目的的一种方法是将所有 kwargs 分配给实例属性,因此:

class BaseClass(object):
    def __init__(self, mark, name, **kwargs):
        self.mark = mark
        self.name = name
        self.__dict__.update(kwargs)

不过,我不建议“真正”这样做。盲目地设置属性很可能会在将来引入微妙的错误(例如在不知不觉中通过传递同名的关键字arg来替换方法)

derivedClass is not in fact derived from baseClass. To subclass in python you must provide the parent class to the class definition thus:

class DerivedClass(BaseClass):
    pass

DerivedClass now inherits the methods of BaseClass, including __init__(). If you do not override a method, calling it on your subclass actually calls the method as defined on the superclass.

So, if you want to allow DerivedClass(name='Jibin'), you need to provide a specialised init():

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

class DerivedClass(BaseClass):
    def __init__(self, mark, name, rank):
        BaseClass.__init__(self, mark, name)
        self.rank = rank

Now, you also want to support additional keyword arguments to DerivedClass() without adding them explicitly. One way to achieve this is to assign all kwargs to instance attributes, thus:

class BaseClass(object):
    def __init__(self, mark, name, **kwargs):
        self.mark = mark
        self.name = name
        self.__dict__.update(kwargs)

I don't advise this 'for real' though. Blindly setting attributes is likely to introduce subtle bugs in the future (such things as unknowingly replacing a method by passing a keyword arg of the same name)

柒夜笙歌凉 2024-12-22 17:54:24

你们尝试过吗
[Python] 将基类转换为派生类

我已经测试过它,似乎它有效。另外,我认为这种方法比下面的方法要好一些,因为下面的方法不执行派生函数的 init 函数。

c.__class__ = CirclePlus

Have you guys tried
[Python] cast base class to derived class

I have tested it, and seems it works. Also I think this method is bit better than below one since below one does not execute init function of derived function.

c.__class__ = CirclePlus
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文