- How to Get Class Name in Python?
- Use type() to get class name in Python
- Use __class__ to get class name in Python
- Bonus – define a custom whoami method
- Как просто получить имя класса в Python
- Способ 1: комбинация __class__ и __name__
- Способ 2: использование функции type() с __name__
- Часто задаваемые вопросы
- Что такое класс в Python?
- Как получить имя класса в Python?
- Есть ли другой способ получить имя класса в Python?
- Как получить имя класса объекта в виде строки в Python?
- How to Get Class Name in Python?
- What is Class in Python?
- Methods to Get Class Name in Python
- 1) Using __class__.__name__
- 2) Using type() and __name__attribute
- 3) Using nested classes
- Summary
- Get Class Name in Python
- Use the type() Function and __name__ to Get the Type or Class of the Object/Instance
- Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance
- Related Article — Python Class
How to Get Class Name in Python?
This blog post will explain how to get class name in Python. There are a few different methods that can help you find the class name of an object.
Before diving in, let’s first remember what class is in Python.
In Object-Oriented Programming (OOP), a class is a blueprint defining the methods and variables of a particular kind of object. Similarly, in Python, a class defines how the particular object should look like, or more precisely, what variables and methods it should contain.
In some cases, you’d want to check the name of the class of a particular object, so let’s find out how to do it.
How to get class name of an object in Python?
The most convenient way to get Python class name is either by using the type() or __class__ method. To get the class name as a string, you will also need to use the __name__ variable regardless of which of the two methods you use.
If you are using the type() method, the syntax is:
type(x).__name__
If you are using the __class__ method, the syntax is:
x.__class__.__name__
x is the object for which you are getting the class name.
In the following sections, I’ll explain these methods in more detail.
Use type() to get class name in Python
One way of finding the Python class name of an object is by using the built-in type() method. The type() method returns the data type of the object passed to it as an argument.
Still, to get the class name as string, you need to access the special built-in __name__ variable. This variable evaluates to the name of the current module. By chaining the type() and __name__ , you get exactly what you want – the Python class name for the current object.
Let’s see it in action. The first example will show you how to get the class name of some well-known Python literals and data structures.
>>> a = 45 >>> type(a).__name__ 'int' >>> b = 'example' >>> type(b).__name__ 'str' >>> c = True >>> type(c).__name__ 'bool' >>> d = [1, 2, 3] >>> type(d).__name__ 'list' >>> e = >>> type(e).__name__ 'dict'
Also, check out this example for a user-defined class. Here we define the simple Book class that accepts the name in the constructor.
class Book: def __init__(self, name): self.name = name book = Book("The Hitchhiker's Guide to the Galaxy") print(type(book).__name__) # Book
As you can see, the type() method in combination with the __name__ variable returned correct class name.
Use __class__ to get class name in Python
Another convenient way to get class name in Python is by using the built-in __class__ attribute. __class__ is an attribute on the object that refers to the class from which the object was created. Since it returns the object, you have to use it again in combination with the __name__ variable to get class name as string.
We’ll use the same examples as in the previous section to show how to use the __class__ attribute.
>>> a = 45 >>> a.__class__.__name__ 'int' >>> b = 'example' >>> b.__class__.__name__ 'str' >>> c = True >>> c.__class__.__name__ 'bool' >>> d = [1, 2, 3] >>> d.__class__.__name__ 'list' >>> e = >>> e.__class__.__name__ 'dict'
Now let’s see it in action with our custom Book class.
class Book: def __init__(self, name): self.name = name book = Book("The Hitchhiker's Guide to the Galaxy") print(book.__class__.__name__) # Book
Same as before, we got the correct class name.
NOTE - If you are still using Python 2, you should stick to using this method of getting class name since it supports old-style and new-style Python classes. Unfortunately, the type() method works only with new-style classes.
Bonus – define a custom whoami method
To make your life a bit easier when working with multiple custom classes, you could implement a custom method to tell you what class or type is particular object. That way, you won’t need to remember how to find the class name every time.
In short, you should define a parent class that will implement the custom, let’s call it – whoami , method. By inheriting the parent class, each child class will have a whoami method available.
In our example, we’ll call the parent class A, and the child class B. Of course, in your case you can have as many children classes as you want in your case.
class A: def whoami(self): return type(self).__name__ class B(A): pass b = B() print(b.whoami()) # B
Как просто получить имя класса в Python
Чтобы получить имя класса экземпляра в Python, вы можете использовать 2 следующих способа.
- используйте комбинацию __class__ и __name__
- используйте функцию 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__.
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
- Use the type() Function and __name__ to Get the Type or Class of the Object/Instance
- 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.