简体   繁体   中英

What's the best way to init class attribute in python3?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM