0

I'm trying to use the variable name of my class inside of a method in my class, but I have no idea how to do it. To better explain here is an example.

class Pet():
    def __init__(self, name, species):
        self.name = name
        self.species = species
        
    def petVar(self):
        print(f"{str(__name__)} is the name of the variable")

pet1 =Pet("peter", "cat")

pet1.petVar()

#output
'__main__ is the name of the variable'

The output I would want here would be 'pet1 is the name of the variable'. I understand it might be confusing why I might would try to do this, but this is a simplified version of my issue which is causing me a larger problem in my code.

Appreciate anyone who can help.

  • 4
    Trying to get the name of the variable you are assigning to is a code smell – Tom McLean Oct 07 '22 at 22:23
  • 2
    In Python, variables are names of objects. There can be more than one name for an object. For example, `pet1 = Pet('peter','cat')` then `pet2 = pet1`. `pet1.petVar()` or `pet2.petVar()` can't know which variable it was called from. `self` will just be yet another name for the `Pet` instance. – Mark Tolonen Oct 07 '22 at 22:27
  • 1
    This may only be possible with some weird trickery by inspecting stack frames to find the line in source that calls "petVar" and then parsing the source to find the variable name. In short: Don't try this. – Michael Butscher Oct 07 '22 at 22:29
  • Welcome to Stack Overflow. The question does not make sense. An object can have **any number of names, including zero** (if it is remembered in some other way, for example by being an element in a list). When the `petVar` method is called, **that method** has **its own name** for the object: `self`. It **cannot access anyone else's name**. – Karl Knechtel Oct 07 '22 at 23:02

1 Answers1

0

If you need the instance name the most easy way to do it is to have a instance field name "name" that will hold the name of the instance.

class Pet:
    def (self, inst_name):
        self.inst_name = inst_name
    def print_inst_name(self):
        print(self.inst_name)

pet1 = Pet("pet1")
pet1.print_inst_name()

Output

pet1

OR

To get the name of the class inside a method within the class You can used a class method by using the decorator @classmethod or by using a instance method and use the "name" field

FOR EXAMPLE:

class Pet:
    # class method
    @classmethod
    def print_class_name(cls):
        print (cls.__name__)
    # instance method
    def print_class_name_inst(self):
        print (self.__class__.__name__)
Maxwell D. Dorliea
  • 1,086
  • 1
  • 8
  • 20