Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dataclasses: trying to understand them in python

I’m learning classes in python. Also trying to learn dataclasses.

from dataclasses import dataclass
class Person():
    name: str
    age: int
    height:  float
    email: str

person = Person('Joe', 25, 1.85, 'joe@dataquest.io')
print(person.name)

Error:

TypeError: Person() takes no arguments

Unsure why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You didn’t decorate your class with the @dataclass decorator you’ve imported, so it’s just a plain old class that has a bunch of annotations but no specific __init__, so it inherits object‘s __init__, which takes no arguments.

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    height: float
    email: str

would have dataclass do its magic to read those annotations and add the constructor and everything else dataclasses do.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading