Python find class of object

How to get the class name of an instance in Python?

The object-oriented procedural programming, including the ideas of classes and objects, is well supported by Python. It offers a crystal-clear program structure and simple code modification. The code can be reused and offers many benefits of abstractions, encapsulation, and polymorphism due to the class’s shareability.

A Python class is a «blueprint» for creating objects in Python is a class.

Getting Class name of an instance in Python

To determine a Python instance’s class name there are two ways −

  • Using the type() function and __name__ function.
  • Using the combination of the __class__ and __name__.

A unique built-in variable called __name__ basically provides the name of the current module in which it is used.

Since Python doesn’t have a main() method like other programming languages like C/C++, Java, and others that are similar, the interpreter sets the value of __main__ to __name__ if the source file is used as the main program.

Читайте также:  Python decorators inside class

In addition, __name__ is set to the name of the importing module if a file is imported from another module.

The following code retrieves the type or class of the object using the type() function and the __name__ variable

Example

class number: def __init__(self, number): self.number = number x = number(1) print (type(x).__name__)

Output

In this article, we wil learn to get the class name of an instance in Python using the above mentioned methods.

Using __class__ .__name__

Python’s __class__ property, which simply refers to the class of the object we want to retrieve, is the first and simplest way to get a class name. Here, we combine the property with the __name__ property to determine the object’s or instance’s class name. The unique Python variable __name__ specifies the name of the current module in which it is utilised.

Note − You must create the object for that class in order to display its name using class.name.

Example

Following is an example to get the class name of an instance in Python using __class__.__name__ method:

class animal: def __init__(self, animal): self.animal = animal l = animal("Lion is the animal") print (l.__class__) print (l.__class__.__name__)

Output

Following is an output of the above code −

Using type() and __name__ attribute

A different approach is to utilise Python’s built-in type() method to determine the object’s type or class. To obtain the class name, you must combine the type() function with the __name__ variable.

Example

Following is an example to get the class name of an instance in Python using type() and __name__ attribute −

class animal: def name(self, name): return name a = animal() print(type(a).__name__)

Output

Following is an output of the above code −

Example

Let’s examine the class name of a simple string as shown in the following example −

d = "Python Program" print(type(d).__name__)

Output

The class of a string instance is “str”, as you can see in the following output −

Example

Use the “count” instance of the itertools module to acquire the class name as shown in the following example −

import itertools d = itertools.count(2) print(type(d).__name__)

Output

Following is an output of the above code −

Example

Find the class of the “lists” instance by defining an empty list as shown in the example mentioned below −

the_list = [] t = type(the_list) name_of_class = t.__name__ print(name_of_class)

Output

Following is an output of the above code −

Example

The class name is also available as a string as shown in the following example −

class S: pass d = S() print(str(d.__class__))

Output

Following is an output of the above code −

Using nested classes (using __qualname__ instead of __name__)

In some cases, you may want to get the class name in a program that has nested classes. In this case, you can retrieve the name of the qualified object by using the __qualname__ attribute rather than the __name__ attribute.

Example

There are two classes listed: «Animal» and «Lion» . Additionally, as shown in the code below, we have created the variable instances for both classes. The Lion’s object is called inside the class «Animal» and given an argument named «a» that is a variable.

The values for the instance Animal and Lion are then set in the class «Animal» object «obj_Animal». Both the method «__name__» and the method «__qualname__» are available in the print function to retrieve the class name and the qualified object name, respectively.

class Animal: def __init__(self, a_name, a): self.a_name = a_name self.obj_Lion = self.Lion(a) class Lion: def __init__(self, obj_Lion): self.obj_Lion = obj_Lion obj_Animal = Animal("Sher", "King") print(obj_Animal. obj_Lion.__class__.__name__) print(obj_Animal. obj_Lion.__class__.__qualname__)

Output

Following is an output of the above code −

Источник

How to Get Class Name in Python?

How to Get Class Name in Python?

Python is well famous to support object-oriented programming including the concepts of classes and objects. It provides a clear program structure and easy modification of code. Since the class is sharable, the code can be reused and also provide different advantages of abstractions, encapsulation, and polymorphism. In this article, we will study the python class and how python get class name of an instance with examples and output. Let’s get started!

What is Class in Python?

Classes are the focal point of OOP and objects are created by Classes. The class can be defined as the description or the definition of the object. The class describes what the object will be but is totally separated from the object itself.

Also, a single class is used to describe multiple objects. For example, we create a blueprint before constructing the house. Similarly, the same blueprint can be used for different houses to be built. The programming works in the flow where first the class is defined which further describes the object. Each class has a name, and its own attribute and behavior.

The method is another term used in classes. Methods are the functions in the classes. They have a specific block of code that can be called and execute a certain task and return the values. The syntax of the class is as given by:

class ClassName: # Statement1 . . . # StatementN 

For example:

class Fruit: def __init__(self, name, color): self.name = name self.color = color def func(self): print("Fruit is " + self.name) f1 = Fruit("Apple", "Red") f1.func()

Methods to Get Class Name in Python

Below are 3 methods by which you can get the class name in python:

1) Using __class__.__name__

The first and easiest method to get a class name in python is by using __class__ property which basically refers to the class of the object we wish to retrieve. Here we combine the property with __name__ property to identify the class name of the object or instance. __name__ is the special variable in python that provides the name of the current module where it is used.

Note that to display the class name you have to create the object for that lass and display its name using class.name. Check out the below example for a better understanding of these methods.

For example:

class fruit: def __init__(self, fruit): self.fruit = fruit a = fruit("orange") print (a.__class__) print (a.__class__.__name__)

2) Using type() and __name__attribute

Another method is to use the type() method which is the in-built python method to find the type or the class name of the object. You have to merge the type() function with the __name__ variable and get the name of the class as shown in the below example:

For example:

class fruit: def __init__(self, fruit): self.fruit = fruit a = fruit("orange") print (type(a).__name__)

3) Using nested classes

There are scenarios where you have nested classes in the program and wish to get a class name. In this situation, you can make use of __qualname__ attribute instead of __name__ attribute to get the name of the qualified object.

For example:

class Fruit: def __init__(self, name, b): self.name = name self.vegetable = self.Vegetables(b) class Vegetables: def __init__(self, vegetable): self.vegetable = vegetable fruit = Fruit("orange", ['potatoes']) print(fruit.vegetable.__class__.__name__) print(fruit.vegetable.__class__.__qualname__)
Vegetables Fruit.Vegetables 

Summary

Object-oriented programming in python provides multiple advantages such as abstraction, polymorphism, etc. It helps to maintain your code easily and error-free providing the better structure and ability to reuse it. This article represents the various methods by which python get class name easily using __class__, type() and __qualname__ methods. It is recommended to learn and understand this method thoroughly and make your programming easy and efficient.

Источник

Get Class Name in Python

Get Class Name in Python

  1. Use the type() Function and __name__ to Get the Type or Class of the Object/Instance
  2. Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance

A class, just like an object constructor, can be defined as a user-defined prototype that is used to create objects. Classes can be created using the keyword class .

A class is a data structure, and it can hold both data members and member methods.

This tutorial will discuss the method to get the class name in Python.

Use the type() Function and __name__ to Get the Type or Class of the Object/Instance

type() is a predefined function that can be used in finding the type or class of an object.

__name__ is a special built-in variable that basically gives the name of the current module where it is used. Since python has no main() function like the other languages like C/C++, Java, and other similar languages, if it is the source file that is executed as the main program, then the interpreter sets the value of __main__ to __name__ . At the same time, when a file is imported from any other module, __name__ is then set to that module’s name.

The type() function and the __name__ variable are used to get the type or class of the object in the following code.

class num:  def __init__(self, num):  self.num = num x = num(1) print (type(x).__name__) 

In Python 3, all created classes are new-style classes, while in Python 2, old-style classes might co-exist with the new-style classes. A new-style class is a class that gets inherited from the instance of the object, while old-style or classic classes are the basic classes that existed before python 2.1.

The above method can work only with new-style classes.

Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance

The __class__ property can also be used to find the class or type of an object. It basically refers to the class the object was created in.

The __name__ can also be used along with __class__ to get the class of the object.

The following code uses both __class__ and __name__ to get the class of an object.

class num:  def __init__(self, num):  self.num = num x = num(1) print (x.__class__) print (x.__class__.__name__) 

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article — Python Class

Источник

Оцените статью