首页 > 解决方案 > 尝试在 Python 中使用条件初始化类变量

问题描述

我正在尝试在 Python 中创建一个类 Statistician。

这个统计学家类有 3 个属性:它们中的每一个都可以有从 0 到 100 的整数值(整数):

  1. 逻辑
  2. 记忆
  3. 有创意

此类将具有以下方法:

Initialization():通过使总和在111到177之间随机分配3个属性值的方法,不包括偶数和5的倍数。该方法将由对象的构造函数启动。

我有这个代码:

import random

class Statisticien:

    def __init__(self):

        a = 0
        b = 0
        c = 0
        somme = a + b + c

        while somme >= 177 and somme <= 111 and (a%2 == 0) and (a%5 == 5) and (b%2 == 0) and(b%5 == 5) and (c%2 == 0) and (c%5 == 5) :
        a = random.randint(0,178)
        b = random.randint(0,178)
        c = random.randint(0,178)

        self.logique = a
        self.memoire = b
        self.creativite = c

    test = Statisticien()
    print(test.logique)
    print(test.memoire
    print(test.creativite)
    >>>
    0
    0
    0

此代码为我的属性 logique、memoire 和 creativite 分配了 0,但我不明白为什么,因为根据我的情况,虽然数字 a、b 和 c 在之后被修改。有人可以帮我理解为什么吗?也许解释如何管理我的问题?

标签: pythonclasswhile-loopinitializationinstance

解决方案


while 条件似乎太复杂了。

尝试这个:

import random

class Statisticien:

    def __init__(self):

        a = 0
        b = 0
        c = 0
        somme = a + b + c

        while (somme <=111 or somme >= 177 or somme%2 == 0 or somme%5 == 0): 
            a = random.randint(0,178)
            b = random.randint(0,178)
            c = random.randint(0,178)

            somme = a + b + c
            self.logique = a
            self.memoire = b
            self.creativite = c

test = Statisticien()
print(test.logique)
print(test.memoire)
print(test.creativite)

推荐阅读