我只是想使其生成器生成四肢数在1到100之间的怪物。我不知道为什么self.numbers不起作用。我在self.numbers中的print语句中始终收到无效的语法错误。
import random
from random import randint
class Monster(object):
def __init__(self):
self.names = random.choice(["Michael", "Amy", "June", "Margaret"])
self.appearances = random.choice(["a beautiful", "a hideous", "a transparent", "a toxic"])
self.animals = random.choice(["dog", "cat", "bird", "fish"])
self.attributes = random.choice(["that can fly.", "that speaks in a human voice.", "that twists unaturally.", "that is too hot to touch."])
self.features = random.choice(["arms", "legs", "tentacles", "heads"])
self.numbers = print random.randint(1, 100)
def __str__(self):
return ' '.join(["The Human", self.names, "is here,", self.appearances,
self.animals, self.attributes, "It has", self.numbers,
self.features,])
# Create 5 unique monsters
M1 = Monster()
M2 = Monster()
M3 = Monster()
M4 = Monster()
M5 = Monster()
# Prints the descriptions of the monsters:
print M1
print M2
print M3
print M4
print M5
input('Press ENTER to exit')
答案 0 :(得分:0)
替换
self.numbers = print random.randint(1, 100)
与
self.numbers = str(randint(1,100))
print函数将打印到外壳中,并且不会创建字符串。您需要使用str()函数将随机生成的数字转换为字符串
您的代码:
import random
from random import randint
class Monster(object):
def __init__(self):
self.names = random.choice(["Michael", "Amy", "June", "Margaret"])
self.appearances = random.choice(["a beautiful", "a hideous", "a transparent", "a toxic"])
self.animals = random.choice(["dog", "cat", "bird", "fish"])
self.attributes = random.choice(["that can fly.", "that speaks in a human voice.", "that twists unaturally.", "that is too hot to touch."])
self.features = random.choice(["arms", "legs", "tentacles", "heads"])
self.numbers = str(randint(1, 100))
def __str__(self):
return ' '.join(["The Human", self.names, "is here,", self.appearances,
self.animals, self.attributes, "It has", self.numbers,
self.features,])
# Create 5 unique monsters
M1 = Monster()
M2 = Monster()
M3 = Monster()
M4 = Monster()
M5 = Monster()
# Prints the descriptions of the monsters:
print M1
print M2
print M3
print M4
print M5
input('Press ENTER to exit')
和结果
The Human Margaret is here, a hideous fish that can fly. It has 65 arms
The Human Michael is here, a toxic fish that is too hot to touch. It has 75 heads
The Human Margaret is here, a transparent dog that can fly. It has 23 tentacles
The Human Margaret is here, a transparent dog that is too hot to touch. It has 64 arms
The Human Margaret is here, a hideous bird that twists unaturally. It has 46 heads
Press ENTER to exit