【问题标题】:Trying to initialize a class variable in Python with conditions尝试在 Python 中使用条件初始化类变量
【发布时间】:2020-10-18 12:47:40
【问题描述】:

我正在尝试在 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

此代码将 0 分配给我的属性 logique、memoire 和 creativite,但我不明白为什么,因为在我的条件下,虽然数字 a、b 和 c 刚刚被修改。有人可以帮我理解为什么吗?或者解释一下如何解决我的问题?

【问题讨论】:

  • 请用适当的缩进复制代码,因为它是python中的一个语法元素,如果它是错误的,一切都是模棱两可的。
  • 任何int x % 5 永远不能等于5

标签: python class while-loop initialization instance


【解决方案1】:

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)

【讨论】:

  • 感谢您的回答。问题是所有 3 个变量 a、b 和 c 都不能是偶数,也不能是 5 的倍数(不是三个的总和)
【解决方案2】:

我终于用这段代码成功了:

import random

class Statisticien:

    def __init__(self):

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

        while (somme >= 177) or (somme <= 111) or (a%2 == 0) or (a%5 == 0) or (b%2 == 0) or (b%5 == 0) or (c%2 == 0) or (c%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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多