Python: How to define a variable in an __init__ fu

2019-07-06 11:46发布

问题:

class TextToNumbers():
    def __init__(self, number):
        self.text = str(number)
        self.chunks = parse_text_to_chunks(self.text)

    def parse_text_to_chunks(text_to_parse):
        #stuff

This is an example of a class I'm building. I want it to define some variables with class methods on initialization. (at least I think that is what I want) I think if I talk about my end goal it is that I have a set of complex information that needs to be available about a class directly at initialization. How do I call a class method at initialization, to define a class variable?

回答1:

If you are looking for a way to call an instance method during initialization, you can use self to call that like this

class TextToNumbers():
    def __init__(self, number):
        self.text = str(number)
        self.chunks = self.parse_text_to_chunks(self.text)
        print self.chunks

    def parse_text_to_chunks(self, text_to_parse):
    # 1st parameter passed is the current INSTANCE on which this method is called
        self.var1 = text_to_parse[1:]
        return self.var1

TextToNumbers(123)

And I believe this is what you really need. But if you want a class method

class TextToNumbers():
    def __init__(self, number):
        self.text = str(number)
        self.chunks = TextToNumbers.parse_text_to_chunks(self.text)
        print self.chunks

    @classmethod
    def parse_text_to_chunks(cls, text_to_parse):
    # 1st parameter passed is the current CLASS on which this method is called
        cls.var1 = text_to_parse[1:]
        return cls.var1

TextToNumbers(123)

But there is no point in creating a class method to initialize a class variable in __init__, since a class variable is shared by all the instances of the class, calling from __init__ will overwrite everytime an object is created.