简体   繁体   English

每次调用此数据类时,如何更改数据类属性?

[英]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__ .当您将数据类中的属性声明为field ,其元数据将放置在ClassExample.__dataclass_fields__ The class object ClassExample does not even have an attribute first , only instances do.类对象ClassExample甚至没有属性first ,只有实例有。 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 .您的第二个类exp共享ClassExample的同一个实例。 If you want it to generate a new one for each instance, you need to do the same thing you did for ClassExample :如果您希望它为每个实例生成一个新实例,您需要执行与ClassExample相同的ClassExample

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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