在 Python 中创建类的实例时,我试图返回字典的值,但我一直返回“None”。
我是 Python 的新手,所以我确信这个问题有一个简单的答案。
运行以下命令后:
class TestTwo(object):
def __init__(self):
self.attributes = {
'age': "",
'name' : "",
'location': ""
}
def your_age(self):
self.attributes['age'] = raw_input("What is your age? > ")
self.your_name()
def your_name(self):
self.attributes['name'] = raw_input("What is your name? > ")
self.your_location()
def your_location(self):
self.attributes['location'] = raw_input("Where do you live? > ")
self.results()
def results(self):
print "You live in %s" % self.attributes['location']
print "Your number is %s" % self.attributes['age']
print "Your name is %s" % self.attributes['name']
d = self.attributes
return d
output = TestTwo().your_age()
print output
我最终得到了这个:
MacBook-Pro-2:python johnrougeux$ python class_test.py
What is your age? > 30
What is your name? > John
Where do you live? > KY
You live in KY
Your number is 30
Your name is John
None
我期待的不是“无”,而是“{'age': '30', 'name': 'John', 'location': 'KY'}”
我错过了什么?
最佳答案
只有 results()
返回一些东西。如果您希望它们也返回一些东西,您需要通过在其他函数中返回它来沿着调用链传递它的返回值:
def your_age(self):
self.attributes['age'] = raw_input("What is your age? > ")
return self.your_name()
def your_name(self):
self.attributes['name'] = raw_input("What is your name? > ")
return self.your_location()
def your_location(self):
self.attributes['location'] = raw_input("Where do you live? > ")
return self.results()
当然,这种链接非常丑陋;但我相信你已经知道了。如果没有,请像这样重写代码:
在每个函数中,只需设置值并且不调用您的其他函数之一。然后添加这样的函数:
def prompt_data(self):
self.your_age()
self.your_name()
self.your_location()
在使用该类的代码中,执行以下操作:
t2 = TestTwo()
t2.prompt_data()
output = t2.results()
关于python - "None"尝试在 Python 中返回 dict 的值时给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611592/