【问题标题】:how can I make a function in a class that returns the object values as a dictionary?如何在将对象值作为字典返回的类中创建一个函数?
【发布时间】: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


    【解决方案1】:

    你应该打电话

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

    改为。

    【讨论】:

      【解决方案2】:

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

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

      输出

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 2019-01-17
        • 2018-02-05
        • 2017-09-24
        • 1970-01-01
        相关资源
        最近更新 更多