method to print name of an instance of a class

I am new to classes and writing one to perform a tracking and timing task. Have looked at this but still having trouble getting one aspect of the functionality to work.

Here's the part of what I've got to demonstrate the problem:

class seperate_trackers():

    def __init__(self): 
        print ("class initiated")

    def print_instance_name(self):
        print (self.__class__.__name__)

Create an instance of it:

track_task1 = separate_trackers()
>> class initiated

Run the method in there:

track_task1.print_instance_name()
>> separate_trackers

That's not what I want!

How can that method be fixed so it returns track_task1 when it is run?


This is not a good idea. If you want your instance to have a name, that should be an attribute of the instance itself (the name of the variabe is just a pointer and it should not represent the object's state).

Try this instead:

# We don't usually use snake case for class names in python (and its 'separate')
class SeparateTrackers():

    def __init__(self, name): 
        self.name = name


instance1 = SeparateTrackers("instance_name")

print(instance1.name) # instance_name

Objects don't know what variables refer to them. There can be any number of references to an object, and none of them is "the real one," they are all equally valid as names for the object. Furthermore, there may be no references that are simple names:

things = [1, "hello", separate_trackers(), 3.14]

There's no useful way to find out what variables refer to an object.


class SeparateTrackers:
  def __init__(self, instance_name):
    self.instance_name = instance_name

  def __str__(self):
    return self.instance_name

所以你可以使用类似的东西

a = SeparateTracker("first instance")
print(a) # print instance's name
链接地址: http://www.djcxy.com/p/40950.html

上一篇: 是否有可能间接访问python中的当前类名?

下一篇: 方法来打印类的实例的名称