Here's an example.
class myclass:
def __init__(self):
self.start = False
def check(self):
return not self.start
def doA(self):
if self.check():
return
print('A')
def doB(self):
if self.check():
return
print('B')
As you see, I want to write the check action in a decorator way, but after i tried many times, I found I can only write the method outside my class. Please teach me how to write it inside the class.
I can write the code in this way:
def check(func):
def checked(self):
if not self.start:
return
func(self)
return checked
class myclass:
def __init__(self):
self.start = False
@check
def doA(self):
print('A')
@check
def doB(self):
print('B')
a = myclass()
a.doA()
a.doB()
a.start = True
a.doA()
a.doB()
but I don't think it's a good practice, I want to defined the check method inside my class.