【发布时间】:2021-03-09 10:59:52
【问题描述】:
我有一个以姓名和年龄为参数的类
class person():
def __init__(self , name , age):
self.name = name
self.age = age
person1 = person('ahmed','18')
print(person1)
我想在该类中创建一个函数以将(所有)值作为字典返回
我在运行代码时得到了什么:
<__main__.person object at 0x000002F4E38DEFD0>
想要的结果:
{'name': 'ahmed', 'age': 18}
我尝试了该解决方案,但没有奏效:
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
【问题讨论】:
标签: python python-3.x oop