[Python] How to pass unpacking as an input parameter to initialize a member class object in...

Discussão em 'Python' iniciado por Stack, Julho 6, 2025.

  1. Stack

    Stack Membro Participativo

    For example, in the following code, I want to pass 6 parameters by unpacking * num to initialize a1, a2, a3 in class A and b1, b2, b3 in class B. However, there will be an error because A only has 4 members. Is there a solution to pass 6 parameters to initialize A, automatically initialize the first 3 parameters a1, a2, a3, and use the last 3 parameters to initialize b1, b2, b3 in member object b? The source of the demand is because I want to use vars (self) to extract all member data of the subclass objects of the Base class, just like the get_data method, so that there is no need to display the member names every time, otherwise there will be too much repetitive code, such as return [self. b1, self. b2, self. b3], because writing each subclass in this way requires handwritten variable names. The example code is as follows. When executing A (* num), an error message will appear indicating that there are too many parameters

    @dataclass
    class Base():
    def __str__(self):
    data = ','.join([str(x) for x in vars(self).values()])
    return data

    def get_data(self):
    return ','.join([str(x) for x in vars(self).values()])
    @dataclass
    class B(Base):
    b1: int = 0
    b2: int = 0
    b3: int = 0

    @dataclass
    class A(Base):
    a1: int = 0
    a2: int = 0
    a3: int = 0
    b: B = None

    num = [1,2,3,4,5,6]
    my_data = A(*num)

    Continue reading...

Compartilhe esta Página