我在python上试用类,但我遇到了名称错误,但我不知道如何解决。当不在课堂上时它可以正常工作,但现在它不起作用我想这是一个明显的问题,或者只是整个事情是错误的,而且我现在看起来很愚蠢,其他变量是我还没有做完的事情所以不要理他们。 (是的,统计信息会直接从辐射中被删除”)
import time, random
class User():
def players():
players = 0
def stats(self):
perks = 20
print ("you have 20 perk points to spend")
print(""" you have several choices of what to spend
them in:
STRENGTH - what it says on the tin
PERCEPTION - awareness
ENDURANCE - how long you can endure something
CHARISMA - yet again what it says on the tin
INTELLIGENCE - how smart you are
AGILITY - how much of a slippery bugger you are
LUCK - how lucky you are""")
strength = int(input("What level is your strength?"))
perks = perks - strength
perception = int(input("What level is your perception?"))
perks = perks - perception
endurance = int(input("What level is your endurance?"))
perks = perks - endurance
charisma = int(input("What level is your charisma?"))
perks = perks - charisma
intelligence = int(input("What level is your intelligence?"))
perks = perks - intelligence
agility = int(input("What level is your agility?"))
perks = perks - agility
luck = int(input("What level is your luck?"))
perks = perks - luck
if perks >= 0:
print ("this works")
elif perks <=-1:
print("this also works")
def __init__(self,username,stats):
self.username = username
self.stats = stats
players +=1
story = "on"
while story == "on":
print ("Start of story")
stats()
Welcome to my story
Traceback (most recent call last):
File "C:/Users/----/----/python/----.py", line 45, in <module>
stats()
NameError: name 'stats' is not defined
>>>
答案 0 :(得分:1)
您的问题是您拥有attribute
stats
和方法stats
,可以将stats
属性重命名为_stats
,并且您还需要例如,从User
类中创建一个对象
class User():
def __init__(self,username,stats):
self.username = username
self._stats = stats
...
def stats(self):
...
user = User('test', 1)
story = "on"
while story == "on":
print ("Start of story")
user.stats() # method
user._stats # attribute
答案 1 :(得分:0)
stats()
是您的类User
的一种方法。这意味着stats()
存在于User
的{{3}}中,但超出范围未定义。
然后存在另一个问题:您的__init__
接受一个具有相同名称(stats
)的参数,然后将stats
设置为self
的属性。这意味着您可以使用传递给stats()
调用的任何内容(设置__init__
时)覆盖方法self.stats = stats
。您应该将此属性重命名,也许重命名为self._stats = stats
。
在您的全球范围内,您从未scope您的课程User
。因此,您可以执行以下操作:
user = User("Jeremy", "whatever your stats are")
story = "on"
while story == "on":
print ("Start of story")
user.stats()
这将解决错误。但是我不确定代码是否会执行您期望的操作。您在stats()
中定义了许多变量,例如strength
等。也许您想将它们定义为self
的属性,所以self.strength = ...
。
然后您可以通过user.strength
等在全局范围内访问它们。