Home >Backend Development >Python Tutorial >How does my code discover the name of an object in Python?

How does my code discover the name of an object in Python?

WBOY
WBOYforward
2023-08-19 14:57:141060browse

How does my code discover the name of an object in Python?

No, there is no way to discover the name of an object in Python. The reason is that objects don't actually have names.

Suppose we have the following code. Here we cannot find the actual instance name. Since both ob1 and ob2 are bound to the same value, we cannot conclude whether the instance names of ob1 or ob2 are the same −

The Chinese translation of

Example

is:

Example

# Creating a Demo Class
class Demo:
   pass

Example = Demo
ob1 = Example()
ob2 = ob1

print(ob2)
print(ob1)

Output

<__main__.Demo object at 0x00000250BA6C5390>
<__main__.Demo object at 0x00000250BA6C5390>

As we saw above, we cannot display the exact name of the object. However, we can display instances and counts as shown in the example below.

Get an instance of a class

In this example, we created a Demo class with four instances -

ob1 = Demo()
ob2 = Demo()
ob3 = Demo()
ob4 = Demo()

We loop through objects in memory −

for ob in gc.get_objects():

Example

Using the isinstance() function, each object will be checked to see if it is an instance of the Demo class. Let's see a complete example -

import gc

# Create a Class
class Demo:
   pass

# Four objects
ob1 = Demo()
ob2 = Demo()
ob3 = Demo()
ob4 = Demo()

# Display all instances of a given class
for ob in gc.get_objects():
   if isinstance(ob, Demo):
      print(ob)

Output

<__main__.Demo object at 0x7f18e74fe4c0>
<__main__.Demo object at 0x7f18e7409d90>
<__main__.Demo object at 0x7f18e7463370>
<__main__.Demo object at 0x7f18e7463400>

Display the number of instances of a class

In this example, we will calculate the instance and display −

Example

import gc

# Create a Class
class Demo(object):
   pass

# Creating 4 objects
ob1 = Demo()
ob2 = Demo()
ob3 = Demo()
ob4 = Demo()

# Calculating and displaying the count of instances
res = sum(1 for k in gc.get_referrers(Demo) if k.__class__ is Demo)
print("Count the instances = ",res)

Output

Count the instances = 4

The above is the detailed content of How does my code discover the name of an object in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete