简体   繁体   中英

Set __init__ attributes based on __init__ arguments

I would like to reduce the number of rows in class definition and create __init __ attributes that have same name as __init __ arguments. Is this possible?

class Num():
    def __init__(self, arg1, arg2):
        self.arg3 = 'three'
        # some magic here

a = Num('one', 'two')  # instance

then

print(a.arg1)  # one
print(a.arg2)  # two
print(a.arg3)  # three

If you wanted to infer it from the parameter list, you could do tricky stuff with locals() :

class Num:
    def __init__(self, arg1, arg2):
        for var, val in locals().items():
            if var != 'self':
                self.__setattr__(var, val)
        self.arg3 = "three"


a = Num('one', 'two')  # instance
print(a.arg1)  # one
print(a.arg2)  # two
print(a.arg3)  # three

A better solution would be to use a dataclass:

from dataclasses import dataclass


@dataclass
class Num:
    arg1: str
    arg2: str
    arg3: str = "three"


a = Num('one', 'two')  # instance
print(a.arg1)  # one
print(a.arg2)  # two
print(a.arg3)  # three

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