简体   繁体   中英

pythonic way to print variables in class Person

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

def show(self):
    print(("Name: {}\nSurname: {}\nAge: {}").format(self.name, self.surname, self.age))

Is there more pythonic way to show these variables by function show?

I don't want spaghetti code when i have 34 variables in class

Not sure if it is more Pythonic or not, but instead of defining show you can override __repr__ (you will need to return that string instead of printing it). Then instead of calling person_obj.show you can simply do print(person_obj) .

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

    def __repr__(self):
        return "Name: {}\nSurname: {}\nAge: {}").format(self.name,     self.surname, self.age)

print(Person('a','b', 'c'))
>> Name: a
   Surname: b
   Age: c

This will display correctly even if you have a list of persons:

print([Person('a', 'b', 'c'), Person('d', 'e', 'f')])
>> [Name: a
    Surname: b
    Age: c, Name: d
    Surname: e
    Age: f]

In the case you don't want to override __str__ and badly need show to print, not return data, it's still more pythonic to use format . I'd make few adjustment for your code:

def show(self):
    person_info = "Name {name}\nSurname {surname}\nAge {age}".format(name=self.name, surname=self.surname, age=self.age)
    print (person_info)

In general it's the same you had, just a bit more explicit.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM