Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在类中生成一个函数,将对象值作为字典返回?_Python_Python 3.x_Oop - Fatal编程技术网

Python 如何在类中生成一个函数,将对象值作为字典返回?

Python 如何在类中生成一个函数,将对象值作为字典返回?,python,python-3.x,oop,Python,Python 3.x,Oop,我有一个以名字和年龄为参数的类 class person(): def __init__(self , name , age): self.name = name self.age = age person1 = person('ahmed','18') print(person1) 我想在该类中创建一个函数,将(所有)值作为字典返回 运行代码时得到的结果: <__main__.person object at 0x000002F4E38DEFD

我有一个以名字和年龄为参数的类

class person():
    def __init__(self , name , age):
        self.name = name
        self.age = age

person1 = person('ahmed','18')
print(person1)
我想在该类中创建一个函数,将(所有)值作为字典返回

运行代码时得到的结果:

<__main__.person object at 0x000002F4E38DEFD0>
我尝试过这个解决方案,但没有成功:

class person():
    def __init__(self , name , age):
        self.name = name
        self.age = age

    def dictionary(self):
        return vars(self)

person1 = person.dictionary('ahmed','18')
print(person1)
它返回一个错误

TypeError: dictionary() takes 1 positional argument but 2 were given

您应该将参数传递给
person
,而不是传递给
dictionary
方法:

person1 = person('ahmed','18').dictionary()
print(person1)
输出

{'name': 'ahmed', 'age': '18'}

您应该将参数传递给
person
,而不是传递给
dictionary
方法:

person1 = person('ahmed','18').dictionary()
print(person1)
输出

{'name': 'ahmed', 'age': '18'}
你应该打电话来

person1 = person('ahmed', '18')
print(person1.dictionary())
相反。

你应该打电话

person1 = person('ahmed', '18')
print(person1.dictionary())
相反