How To Access "self" Inside The Scope Of A Class?
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 instan
Solution 1:
You can't, but you can define methods with different names and expose them under certain circumstances. For example:
classX(object):def__init__(self, flag):
ifflag: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'
Solution 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.
Solution 3:
You cannot do that, but to define a method on the fly you can use types.MethodType
:
from types import MethodType
deftrueMethod(self):
print"The true method was defined."deffalseMethod(self):
print"The false method was defined."classX():
def__init__(self, x):
self.x = x
if self.x:
self.trueMethod = MethodType(trueMethod, self, X)
elifnot self.x:
self.falseMethod = MethodType(falseMethod, self, X)
Solution 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]
.
Post a Comment for "How To Access "self" Inside The Scope Of A Class?"