Ericson Willians
Ericson Willians

Reputation: 7845

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

Upvotes: 2

Views: 1101

Answers (4)

Neel
Neel

Reputation: 21243

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

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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)   

Upvotes: 2

icktoofay
icktoofay

Reputation: 129011

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'

Upvotes: 3

BrenBarn
BrenBarn

Reputation: 251383

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.

Upvotes: 3

Related Questions