首页 > 解决方案 > 通过调用随机名称使用类

问题描述

我得到错误打印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)

标签: pythonclassrandom

解决方案


因为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)

推荐阅读