0

I did this to represent a person using typing.NamedTuple:

from typing import NamedTuple


class Phone(NamedTuple):
    residential: str
    mobile: str


class Person(NamedTuple):
    name: str
    last_name: str
    phone: Phone

    @property
    def full_name(self) -> str:
        return f'{self.name} {self.last_name}'
    

edson = Person('Edson', 'Pimenta', Phone('1111-1111', '99999-9999'))

print(edson.full_name)  # Edson Pimenta

And it worked.

The thing is that I've seen lots of people saying that NamedTuples aren't capable of implementing user methods, new ones, like methods that would change any field for example, cause their fields are immutable just like in tuples.

I want to understand NamedTuples before studying Dataclasses more deeply, so I'll know more alternatives to "solve" primitive obsession problems.

Are properties the only available option or there's something happening here that I don't understand?

Are properties even considered methods?

eddyxide
  • 13
  • 4

0 Answers0