Home > front end >  Use class by calling random name
Use class by calling random name

Time:10-20

I get error printing result.age, why? How I can fix it?

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)

CodePudding user response:

Because result is not one of your objects. It's just a string. You can do it like this. Note that I made a list of objects, not a list of strings.

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)

CodePudding user response:

First, your list name only contains strings, not the objects (Bob, Robert, and Tom) you created. So use [Bob, Robert, Tim] instead (note a lack of quotes).

Second, the result would be a list (with varying length), not a single object chosen from the pool. To print the age of the items in the list, you would need to use some form of loop; for, list comprehension, or the like.

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.
  • Related