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())
相反