简体   繁体   中英

How can I make dataclass property change every time I call this dataclass?

I have a trouble getting the different value from dataclass that contains another dataclass everytime its called. I'm using this dataclass later in a code to make different numbers for the same variable.

My code:

@dataclass
class ClassExample:
    first: int = field(default_factory=lambda: random.choice([1, 2, 3]))
    second: int = field(default_factory=lambda: random.randint(1, 6))


@dataclass
class exp:
    sum_s = ClassExample()


# it'll be the same output for each iteration
for _ in range(3):
    print("first:", exp().sum_s.first) # Output: first: 2, first: 2, first: 2
    print("second:", exp().sum_s.second) # Output: second: 1, second: 1, second: 1

What I want:

first: 2 
second: 1
first: 3 
second: 4
first: 1
second:5

How can I achieve that?

When you declare an attribute in a dataclass as field , its metadata is placed in ClassExample.__dataclass_fields__ . The class object ClassExample does not even have an attribute first , only instances do. You see this when you get

AttributeError: type object 'ClassExample' has no attribute 'first'

You need to instantiate the class to get the initializer to run, eg:

ClassExample().first

Your second class, exp , shares the same instance of ClassExample . If you want it to generate a new one for each instance, you need to do the same thing you did for ClassExample :

@dataclass
class exp:
    sum_s = field(default_factory=ClassExample)

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