Python Forum

Full Version: Printing Object Names
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all

I am slowly moving ahead with my python journey. I wanted to ask the following regarding Object Oritentation.

Question 1)

I have created a class called human which when instantiated requires the attributes sex, eye color, height.

I have created 2 x methods one which calculates the age and one method that just prints all the objects attributes to the screen.

from datetime import date

class human():

    
    def __init__(self, sex, eyecolor, height, yearborn):
        self.sex = sex
        self.eyecolor = eyecolor
        self.height = height
        self.yearborn = yearborn
        
        print(self.sex, self.eyecolor, self.height, self.yearborn)
        
        
    def age(self):
        currentdate = date.today()
        a = currentdate.year - self.yearborn
        return a
    
    
    
    def display(self):
        print(self.sex)
        print(self.eyecolor)
        print(self.height)
        print(self.yearborn) 
When I create an object I use the following code:-

import humanclass
Tom = humanclass.human("Male","Green", 173, 1994)
I get the following output:-

Male Green 173 1994
My question is this, is there anyway I can include the name of the object in the def __init__ function so that when python prints the attributes out using the code:-
print(self.sex, self.eyecolor, self.height, self.yearborn)
whatever the user called the object name is also printed out in this case Tom?

Thank you.
Here a example.
from datetime import date

class Human():
    def __init__(self, sex, eyecolor):
        self.sex = sex
        self.eyecolor = eyecolor

    def age(self):
        currentdate = date.today()
        a = currentdate.year - self.yearborn
        return a

    def __str__(self):
        return f'Sex is {self.sex} with {self.eyecolor} eyecolor'

    def __repr__(self):
        return (f'Human({self.sex!r}, {self.eyecolor!r})')
Usage test.
>>> Tom = Human("Male", "Green")

>>> # Call __repr__
>>> Tom
Human('Male', 'Green')

>>> # Call __str__
>>> print(Tom)
Sex is Male with Green eyecolor
So it's fine/advisable that a Class has both have __str__ and __repr__.
__str__ For textual representation that is human readable.
__repr__ Is intended more as a debugging aid for developers,
and for that it needs to be as explicit as possible about what this object is.
The variable/value relationship is one way. Tom knows about the human object it references, but the object has no knowledge of Tom. If you want human to have a name, give it a nane attribute
(May-08-2021, 09:31 PM)deanhystad Wrote: [ -> ]The variable/value relationship is one way. Tom knows about the human object it references, but the object has no knowledge of Tom. If you want human to have a name, give it a nane attribute

Hi deanhystad

Thank you for your reseponse.

Can I ask what is a nane attribute?

Thanks
(May-08-2021, 06:15 PM)JoeDainton123 Wrote: [ -> ]Hello all

I am slowly moving ahead with my python journey. I wanted to ask the following regarding Object Oritentation.

Question 1)

I have created a class called human which when instantiated requires the attributes sex, eye color, height.

I have created 2 x methods one which calculates the age and one method that just prints all the objects attributes to the screen.

from datetime import date

class human():

    
    def __init__(self, sex, eyecolor, height, yearborn):
        self.sex = sex
        self.eyecolor = eyecolor
        self.height = height
        self.yearborn = yearborn
        
        print(self.sex, self.eyecolor, self.height, self.yearborn)
        
        
    def age(self):
        currentdate = date.today()
        a = currentdate.year - self.yearborn
        return a
    
    
    
    def display(self):
        print(self.sex)
        print(self.eyecolor)
        print(self.height)
        print(self.yearborn) 
When I create an object I use the following code:-

import humanclass
Tom = humanclass.human("Male","Green", 173, 1994)
I get the following output:-

Male Green 173 1994
My question is this, is there anyway I can include the name of the object in the def __init__ function so that when python prints the attributes out using the code:-
print(self.sex, self.eyecolor, self.height, self.yearborn)
whatever the user called the object name is also printed out in this case Tom?

Thank you.


Hi snippsat

Thanks for the response.

It took me a while get my head around the __str__ and __repr__ but I do get it. I have to admit that I still prefer using my display method as I find it a little easier to understand but I do recognise that this is not the true "pythonic" way.

Thanks
I almost never use __str__ or __repl__ except when I am debugging code. Not because these have a bad format, but because I seldom find use for a string representation of an object. You should never have a display function for a class because you almost never want to print to stdout. You want to format the data for a GUI display or you want to write it to a file or you want it displayed on a web page. Let the class do what is needed for the class, and let something else worry about how to display the class.

Sorry about "nane". That was a typo. I meant "name". If you want your class to know about names, it should have a name attribute. This code has three name attributes; first_name, last_name and name().
from datetime import datetime

class Person():
    """Information about a person"""
    def __init__(self, last_name, first_name, dob):
        self.last_name = last_name
        self.first_name = first_name
        self.dob = datetime.strptime(dob, '%B %d, %Y')

    def name(self):
        """Return full name"""
        return f'{self.first_name} {self.last_name}'

    def age(self):
        """Return current age"""
        return int((datetime.now() - self.dob).days / 365.25)

    def __str__(self):
        """Return pretty string representation of Person"""
        return f'{self.name()} age={self.age()}'

SAM = Person('Sam', 'Uncle', 'July 4, 1776')

print(SAM)