通过调用随机名称来使用类



我得到错误打印result.age,为什么?我怎样才能修好它?

import random
names = ['Bob', 'Robert', 'Tom']
result = random.choices(names, weights=[5, 10, 12], k=random.randint(1, 3))
print(result)
class People:
def __init__(self, age, city):
self.age = age
self.city = city
Bob = People('23', 'NewYork')
Robert = People('73', 'Boston')
Tom = People('43', 'Oslo')
print(result.age)

因为result不是您的对象之一。它只是一个字符串。你可以这样做。注意,我创建了一个对象列表,而不是字符串列表。

import random
class People:
def __init__(self, age, city):
self.age = age
self.city = city
Bob = People('23', 'NewYork')
Robert = People('73', 'Boston')
Tom = People('43', 'Oslo')
names = [Bob, Robert, Tom]
result = random.choices(names, weights=[5, 10, 12], k=random.randint(1, 3))
print(result)
print(result.age)

首先,列表name只包含字符串,而不包含您创建的对象(Bob,RobertTom)。因此,请使用[Bob, Robert, Tim]代替(注意缺少引号)。

第二,结果将是一个列表(具有可变长度),而不是从池中选择的单个对象。要打印列表中项目的年龄,需要使用某种形式的循环;for,列表推导式,或类似的

import random
class People:
def __init__(self, age, city):
self.age = age
self.city = city
Bob = People('23', 'NewYork')
Robert = People('73', 'Boston')
Tom = People('43', 'Oslo')
friends = [Bob, Robert, Tom]
result = random.choices(friends, weights=[5, 10, 12], k=random.randint(1, 3))
output = [p.age for p in result]
print(output) # ['73', '73', '23']; The outpupt may vary from time to time.

最新更新