我只想在我的字符串中间输入一个随机数



我只是想让我的生成器生成四肢数量在 1 到 100 之间的怪物。我不知道为什么self.numbers不起作用。我在 self.numbers 中的打印语句中不断收到无效的语法错误。

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')

替换

self.numbers = print random.randint(1, 100)

self.numbers = str(randint(1,100))

打印函数将打印到外壳中,并且不会创建字符串。您需要的是使用函数 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

最新更新