python - 尝试在 Python 中使用条件初始化类变量
问题描述
我正在尝试在 Python 中创建一个类 Statistician。
这个统计学家类有 3 个属性:它们中的每一个都可以有从 0 到 100 的整数值(整数):
- 逻辑
- 记忆
- 有创意
此类将具有以下方法:
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 在之后被修改。有人可以帮我理解为什么吗?也许解释如何管理我的问题?
解决方案
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)
推荐阅读
- visual-studio-code - why there is no selection when I click F5 to run program in vscode
- python - 如何清理这张图片(opencv-python)?
- java - 数组只打印某些元素而不打印其他元素
- java - 如何更快地处理 BufferedImage
- javascript - 减少可能是异步且具有回调的函数数组
- javascript - react-bootstrap:使用带有不同消息的选项卡
- visual-studio - 从 TFVC 源代码管理中排除 Nuget 包的步骤是什么?
- node.js - 如何在同一个项目中设置开发数据库连接和生产 - Node JS + MongoDB + Mongoose
- python - 使用 Tornado、Python 的同步 API 调用
- c# - 动态创建标签