Reputation: 1339
There are two methods:
1:
def get(params):
res = "do_something"
return res
class A():
a = get(params)
a=A()
2:
class A():
a = ""
@classmethod
def Init(cls,params):
res = "do_something"
cls.a = res
a=A()
a.Init()
I don't know how to choose.Or is there something better?
Upvotes: 0
Views: 59
Reputation: 29071
Class attributes are supposed to be static properties that are shared among all the instances and don't change values (eg, num_sides
for all Square
instances). So, it's a good policy to initialize them once, on class level.
The classmethod
on the other hand is mainly supposed to be used for alternative constructors. Although you get access to the class, your main objective is initializing an instance. Assigning a class attribute in a such function is confusing to the reader. Additionally, it initialises the value every time this constructor is called.
Overall, the first method is better.
Upvotes: 2