How to reference class variable name in class method definition in python?

Question:

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.

Asked By: CuriousCoder

||

Answers:

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__)
Answered By: Maxwell D. Dorliea
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.