Return class name python

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.

Читайте также:  Css подвинуть блок влево

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.

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.

Источник

Как просто получить имя класса в Python

Чтобы получить имя класса экземпляра в Python, вы можете использовать 2 следующих способа.

  1. используйте комбинацию __class__ и __name__
  2. используйте функцию type() в сочетании с __name__.

Способ 1: комбинация __class__ и __name__

В Python вы можете получить имя класса из экземпляра или самого класса, используя атрибут __class__ вместе с атрибутом __name__.

В этом примере мы определяем MainClass и создаем экземпляр с именем my_instance.

Чтобы получить имя класса из экземпляра, мы обращаемся к атрибуту __class__ экземпляра, за которым следует атрибут __name__ класса.

В качестве альтернативы мы можем получить имя класса непосредственно из класса, обратившись к его атрибуту __name__. Оба метода предоставляют имя класса в виде строки.

Способ 2: использование функции type() с __name__

Вы также можете использовать функцию type() и атрибут __name__, чтобы получить имя класса экземпляра в Python.

В этом примере мы определяем MainClass и создаем экземпляр с именем my_instance.

Чтобы получить имя класса из экземпляра, мы использовали функцию type(), которая возвращает класс экземпляра, а затем обратились к атрибуту __name__, чтобы получить имя класса в виде строки.

Часто задаваемые вопросы

Что такое класс в Python?

Класс в Python — это план для создания объектов. Он определяет набор общих атрибутов и методов для всех объектов этого типа.

Как получить имя класса в Python?

Вы можете использовать атрибут __name__, чтобы получить имя класса в Python. Например, если у вас есть класс, определенный как MainClass:, вы можете получить его имя, используя MainClass.__name__.

Есть ли другой способ получить имя класса в Python?

Да, вы можете использовать функцию type() для получения имени класса в Python. Например, если у вас есть объект obj и вы хотите получить имя его класса, вы можете использовать type(obj).__name__.

Как получить имя класса объекта в виде строки в Python?

Чтобы получить имя класса объекта в виде строки в Python, используйте функцию type() в функции для динамического получения имени класса объекта. Например, вы можете определить функцию, которая принимает объект в качестве аргумента и возвращает имя его класса, используя type(obj).__name__.

Источник

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