Home > OS >  Python couldn't make conditional class?
Python couldn't make conditional class?

Time:08-06

class someclass:
    def __init__(self, alpha):
        self.alpha = alpha
    if self.alpha == 0 :
        def first(self) :
            print (self.alpha)
    else :
        def second(self):
            print ('nothing')

I want make some class like this. Even in my opinion this code looks ridiculous. I want to know this is possible or not. please give me any suggestion. thanks.

CodePudding user response:

You want to dynamically add a method to your class depending on an initialization value. There are a couple of ways to handle this. The first is to use setattr within the __init__.

def first(self):
    print(self.alpha)

def second(self):
    print('nothing')

class Someclass:
    def __init__(self, alpha):
        self.alpha = alpha

        if self.alpha == 0:
            setattr(self, 'first', first)
        else:
            setattr(self, 'second', second)

This is a bit of an anit-pattern and will not work with linters.

Another option is to have different subclasses and use a factory pattern to instantiate the objects.

class Someclass:
    def __init__(self, alpha):
        self.alpha = alpha

class Firstclass(Someclass):
    def first(self):
        print(self.alpha)

class Secondclass(Someclass):
    def second(self):
        print('nothing')

def make_someclass(alpha):
    if alpha == 0:
        return Firstclass(alpha)
    else:
        return Secondclass(alpha)
  • Related