使用以前初始化的属性初始化的类实例

2024-04-27 13:44:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有点复杂。我希望海盗属性的值为真,如果其他两个属性在求和和乘以某个因子时高于某个数字

例如,可能我只希望当social*0.6+fixed大于5时海盗属性为True,否则为false

import random

class consumer(object):
"""Initialize consumers"""
    def __init__(self, fixed, social,pirate):
        self.social = social
        self.fixed = fixed
        self.pirate = pirate

"""Create an array of people"""
for x in range(1,people):
    consumerlist.append(consumer(random.uniform(0,10),random.uniform(0,10),True))
    pass

Tags: 代码selffalsetrue属性consumersocial数字
2条回答

针对Moses的回答:使用计算属性比仅在初始化时计算盗版值更安全。当用@property属性装饰一个方法时,它充当一个属性(你不必像方法那样使用括号),当社会成员在之后被更改时,它总是最新的

class Consumer(object):

    def __init__(self, fixed, social):
        self.fixed = fixed
        self.social = social

    @property
    def pirate(self):
        return self.social * 0.6 + self.fixed > 5

consumer1 = Consumer(1, 12)
print("Value of pirate attribute: " + str(consumer1.pirate))

您需要存储fixedsocial的随机值,然后将它们用于生成pirate的比较:

for x in range(1,people):
     fixed = random.uniform(0,10)
     social = random.uniform(0,10)
     pirate = (social * 0.6 + fixed) > 5 # boolean
     consumerlist.append(consumer(fixed, social, pirate))

你那张通行证是多余的

相关问题 更多 >