python - "None"尝试在 Python 中返回 dict 的值时给出

标签 python oop class dictionary return

在 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/

相关文章:

class - 项目管理中关系类型的UML类图

java - 如何创建对类的引用数组,并在数组中存储其他几个对象的引用值?

python - Azure Functions : Exception while executing function: Functions. x <--- 结果:失败异常:ModuleNotFoundError:没有名为 '_cffi_backend' 的模块

python - 使用 % 字典格式化多行字符串

language-agnostic - 这个图案有名字吗?

c++ - 当调用该类的方法时,该类的指针 "this"变为 null C++

javascript - 使用 JQuery 更改元素的类

javascript - 更改spynner用户代理不起作用

python - adbapi 连接池限制

c++ - 谁应该了解对方?