Ahmed
Ahmed

Reputation: 53

how can I make a function in a class that returns the object values as a dictionary?

I have a class that takes name and age as arguments

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

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

I want to make a function in that class to return (all) the values as a dictionary

what I get when I run the code:

<__main__.person object at 0x000002F4E38DEFD0>

desired result :

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

I tried that solution but it didn't work:

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)

it returns an error

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

Upvotes: 0

Views: 86

Answers (2)

Captain Trojan
Captain Trojan

Reputation: 2921

You should be calling

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

instead.

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

You should pass the arguments to person, not to the dictionary method:

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

Outputs

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

Upvotes: 1

Related Questions