擅长:python、mysql、java
<p>deceze的评论已经解释了为什么这没有反映在子类上。你知道吗</p>
<p>一种解决方法是,您可以在decorator端构建逻辑。你知道吗</p>
<p>像这样的。你知道吗</p>
<pre><code> def decorator(_func=None, *, variable):
def decorator_func(func):
def wrapper(self, *args, **kwargs):
variable_value = getattr(self.__class__, variable)
print(variable_value)
# You can use this value to do rest of the work.
return func(self, *args, **kwargs)
return wrapper
if _func is None:
return decorator_func
else:
return decorator_func(_func)
</code></pre>
<p>同时将decorator语法从<code>@decorator(variable=variable)</code>更新为<code>@decorator(variable='variable')</code></p>
<pre><code>class Base:
variable = None
@decorator(variable='variable')
def function(self):
pass
</code></pre>
<p>演示</p>
<pre><code>b = Base()
b.function() # This will print `None`.
</code></pre>
<p>让我们试试子类</p>
<pre><code>b = Child()
b.function() # This will print `1`.
</code></pre>