gpt4 book ai didi

Python 装饰器 : how to use parent class decorators in a child class

转载 作者:行者123 更新时间:2023-12-04 11:43:21 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Accessing a decorator in a parent class from the child in Python

(2 个回答)


6年前关闭。




备注 :

另一个问题的已接受答案显示了如何使用父装饰器。

这个问题的公认答案显示将装饰器移动到模块范围。

编辑:使用前面的例子是个坏主意。希望这更清楚:

class A:
def deco( func ):
print repr(func)
def wrapper( self, *args ):
val = func( *args )
self.do_something()
return val
return wrapper

def do_something( self ):
# Do something
print 'A: Doing something generic for decoration'

@deco
def do_some_A_thing ( self ):
# Do something
print 'A: Doing something generic'

class B ( A ):

@deco
def do_some_B_thing( self ):
# Do something
print "B: Doing something specific"

a = A()
b = B()
a.do_some_A_thing()
b.do_some_B_thing()

#Expected Output:
#A: Doing something generic
#A: Doing something generic for decoration
#B: Doing something specific
#A: Doing something generic for decoration

此代码生成 NameError: name 'deco' is not defined inside B.
装饰器需要在类范围内,因为我需要访问存储的状态。

第三次编辑:根据斯文的建议,我尝试了这个:
class A:
def deco( func ):
def wrapper( self, *args ):
val = func( *args )
self.do_something(*args)
return val
return wrapper

def do_something( self ):
# Do something
print 'A: Doing something generic for decoration'

@deco
def do_some_A_thing ( self ):
# Do something
print 'A: Doing something generic'

deco = staticmethod(deco)

class B ( A ):

@A.deco
def do_some_B_thing( self ):
# Do something
print "B: Doing something specific"



a = A()
b = B()
a.do_some_A_thing()
b.do_some_B_thing()

#Expected Output:
#A: Doing something generic
#A: Doing something generic for decoration
#B: Doing something specific
#A: Doing something generic for decoration

我现在有 TypeError: do_some_A_thing() 只需要 1 个参数(给定 0)。任何指针?

最佳答案

问题是继承适用于实例属性查找,而不适用于类定义。所以当你尝试在 B 中用 A.deco 进行装饰时,它找不到它。解决方法是移动deco超出模块范围,因为名称 self 没有任何魔力,您可以继续使用它。您还需要显式传递 selffunc , 你会做 不是 需要传入self.do_something() .这是更新的代码:

def deco( func ):
print repr( func )
def wrapper( self, *args ):
val = func( self, *args )
self.do_something()
return val
return wrapper

class A:
def do_something( self ):
# Do something
print 'A: Doing something generic for decoration'

@deco
def do_some_A_thing ( self ):
# Do something
print 'A: Doing something generic'

class B ( A ):

@deco
def do_some_B_thing( self ):
# Do something
print "B: Doing something specific"

a = A()
b = B()
a.do_some_A_thing()
b.do_some_B_thing()

关于Python 装饰器 : how to use parent class decorators in a child class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7473096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com