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

WBOY
Release: 2023-08-19 14:57:14
forward
997 people have browsed it

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)
Copy after login

Output

<__main__.Demo object at 0x00000250BA6C5390>
<__main__.Demo object at 0x00000250BA6C5390>
Copy after login

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()
Copy after login

We loop through objects in memory −

for ob in gc.get_objects():
Copy after login

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)
Copy after login

Output

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

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)
Copy after login

Output

Count the instances = 4
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!