Python:如何使用类方法在__init__函数中定义变量? [英] Python: How to define a variable in an __init__ function with a class method?
问题描述
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
$ b b
这是我正在构建的类的示例。我想让它定义一些变量与类方法初始化。 (至少我认为这是我想要的)我想如果我谈论我的最终目标是,我有一组复杂的信息,需要在初始化时直接提供一个类。如何在初始化时调用类方法来定义类变量?
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?
推荐答案
如果您正在寻找一种方法调用一个实例方法在初始化期间,您可以使用 self
来调用像这样
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)
但是没有必要创建一个类方法来初始化一个类变量在 __ init __
中,因为类变量由该类的所有实例共享,所以从 __ init __
一个对象被创建。
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.
这篇关于Python:如何使用类方法在__init__函数中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!