Dataclasses: trying to understand them in python

Advertisements

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.

>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.

Leave a ReplyCancel reply