Python: How to define a variable in an __init__ function with a class method?

那年仲夏 提交于 2019-12-10 19:08:07

问题


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.



来源:https://stackoverflow.com/questions/21896957/python-how-to-define-a-variable-in-an-init-function-with-a-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!