class Foo():
help_message = ""
def Help_Decorator(func):
def wrapper(data, context, caller):
try:
if data[0] == "help":
return(help_message) #<--- cannot access this locally
else:
return func(data,context,caller)
except:
return func(data,context,caller)
return wrapper
class Bar(Foo):
help_message = "A real help message!"
@foo.Help_Decorator
def Run(data,context,caller):
pass
How can I access Bar's help_message from within my Help_Decorator without passing it as a parameter in Run
?
Since Run
is an instance method, data
is a Bar
instance. Normally this would be called self
by convention, but giving it a different name doesn't change the semantics of the function call.
You should therefore be able to access data.help_message
in your wrapper
function. (I would also expect that data[0]
gives you a TypeError
unless Bar
has implemented __getitem__
.)
The first parameter passed to the wrapper is an instance of the Run class, you should add self as the first parameter. Then you can refer to self.help_message and it will return the help_message defined in the Run class. Your example would become:
class foo():
help_message = ""
def Help_Decorator(func):
def wrapper(self, data, context, caller):
try:
if data[0] == "help":
return(self.help_message) #<--- cannot access this locally
else:
return func(data,context,caller)
except:
return func(data,context,caller)
return wrapper
class Bar():
help_message = "A real help message!"
@foo.Help_Decorator
def Run(data,context,caller):
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.