问题
I've crossed an interesting problem.
Suppose we have a class, and in its constructor we take a boolean as an argument. How can I define methods inside the class based on the instance's condition/boolean? For example:
class X():
def __init__(self, x):
self.x = x
if self.x == true: # self is unreachable outside a method.
def trueMethod():
print "The true method was defined."
if self.x == false: # self is unreachable outside a method.
def falseMethod():
print "The false method was defined."
回答1:
You can't, but you can define methods with different names and expose them under certain circumstances. For example:
class X(object):
def __init__(self, flag):
if flag:
self.method = self._method
def _method(self):
print "I'm a method!"
Testing it:
>>> X(True).method()
I'm a method!
>>> X(False).method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'X' object has no attribute 'method'
回答2:
No, because self
refers to an instance, and there are no instances yet at the time the class is defined.
There are ways to achieve similar effects (like renaming, adding or deleting methods on a per-instance basis within __init__
), but there's no real reason to do this anyway.
回答3:
You cannot do that, but to define a method on the fly you can use types.MethodType
:
from types import MethodType
def trueMethod(self):
print "The true method was defined."
def falseMethod(self):
print "The false method was defined."
class X():
def __init__(self, x):
self.x = x
if self.x:
self.trueMethod = MethodType(trueMethod, self, X)
elif not self.x:
self.falseMethod = MethodType(falseMethod, self, X)
回答4:
You can create dict and on the bases of value you can access function like
def __init__(self, x):
self.x = x
self.my_dict = {True : lambda *a : print "True method", False: lambda *a: print "False method"}
Then you can access self.my_dict[self.x]
.
来源:https://stackoverflow.com/questions/22165529/how-to-access-self-inside-the-scope-of-a-class