Search code examples
pythonclassscopeinstanceself

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 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."

Solution

  • 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'