You can take advantage of the classes' internal __dict__
property to avoid typing all of the variables twice. Additionally, it's best to use the __repr__
function for representing your class:
class Person(object):
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
def __repr__(self):
return '\n'.join([
'Name: {name}',
'Surname: {surname}',
'Age: {age}'
]).format(**self.__dict__)
john = Person('John', 'Doe', 42)
print(john)
Another step of abstraction you could take to avoid hardcoding the format string is to create a list of the properties that identify the instance and use them as follows:
class Person(object):
_identifiers = ('name', 'surname', 'age')
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
def __repr__(self):
return '\n'.join(
'{k}: {v}'.format(k=key.capitalize(), v=self.__dict__[key])
for key in self._identifiers
)
john = Person('John', 'Doe', 42)
print(john)