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

1 python oop dictionary return class

我正在尝试在Python中创建类的实例时返回dict的值,但我不断返回"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
Run Code Online (Sandbox Code Playgroud)

我最终得到了这个:

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
Run Code Online (Sandbox Code Playgroud)

而不是"无",我期待"{'年龄':'30','名字':'约翰','位置':'KY'}"

我错过了什么?

Thi*_*ter 6

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()
Run Code Online (Sandbox Code Playgroud)

当然这种链条非常难看; 但我相信你已经知道了.如果没有,请重写您的代码,如下所示:

在每个这些功能,只需设置值,也不会叫你的其他功能之一.然后添加如下函数:

def prompt_data(self):
    self.your_age()
    self.your_name()
    self.your_location()
Run Code Online (Sandbox Code Playgroud)

在使用该类的代码中,执行以下操作:

t2 = TestTwo()
t2.prompt_data()
output = t2.results()
Run Code Online (Sandbox Code Playgroud)