python如何声明变量,Python:如何使用类方法在__init__函数中定义变量?

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值