【问题标题】:How to make python decorator work with inherited classes如何使 python 装饰器与继承的类一起工作
【发布时间】:2019-07-24 20:19:02
【问题描述】:

我有一段这样的代码,但它不起作用

我正在尝试在这里为某个类的实例提供一个唯一的 id。

def countit(Cls):
  class CC(Cls):
    count = 0
    def __init__(self,*args):
      super(CC, self).__init__(*args)
      self.id = CC.count 
      CC.count += 1
  return CC

class BaseCls(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y

@countit
class Cls(BaseCls):
    def __init__(self,x,y,z):
        super(Cls, self).__init__(x,y)
        self.z=z 

c = Cls(1,2,3) 

我遇到了这样的错误

Traceback (most recent call last):
  File "test.py", line 55, in <module>
    c = Cls(1,2,3) 
  File "test.py", line 35, in __init__
    super(CC, self).__init__(*args)
  File "test.py", line 48, in __init__
    super(Cls, self).__init__(x,y)
TypeError: __init__() missing 1 required positional argument: 'z'

【问题讨论】:

  • 这对于装饰器来说根本不是一个好的用例。

标签: python python-3.x decorator python-decorators


【解决方案1】:

错误是因为装饰器使用 *args 调用装饰类的基类的构造函数。在这种情况下,z 是意外的。

如果您想向基类和派生类添加功能,建议使用 mixins 而不是装饰器。

【讨论】:

    【解决方案2】:

    删除你传递给 super 的参数,它们是不必要的。它应该可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 2011-03-23
      • 2016-03-06
      • 2011-09-18
      • 2018-01-20
      • 2016-12-05
      • 2011-03-01
      • 2019-12-07
      • 2017-08-01
      • 2018-01-27
      相关资源
      最近更新 更多