1

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

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.

  • In Python, __repr__ is a special method used to represent a class's objects as a string. ... According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging – Lalit kumar May 08 '21 at 18:26
  • 1
    Does this answer your question? [How can I get the name of an object in Python?](https://stackoverflow.com/questions/1538342/how-can-i-get-the-name-of-an-object-in-python) – Stuart May 08 '21 at 18:27

2 Answers2

1

No.

Tom is a variable name and has nothing to do with your human object, other than holds a reference for it. If you want the object to know that it is Tom, add a name (or similar) input for it.

As a side note, you should use the def __str__(self): method to your class that will return the string you want to show when you "print" your object (instead of your display method)

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
0

You can create a dictionary. Below I provided an example of how this can be done

class Shape:
    def __init__(self,sides):
        self.sides = sides
    def display(self,name):
        return self.sides,name
objs = {"square":Shape(4)}
print(objs["square"].display("squares"))
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44