type(object).__name__ # is equivalent to: object.__class__.name
Generally, calling special attributes (i.e. those starting and ending with double underscores) directly is discouraged. Therefore, you should use the
type() function instead of
__class__ wherever possible. However, same is not true for
__name__ as there's no function alternative for it.
For example, you can check the class name for a string like so:
name = "John Doe" print(type(name).__name__) # "str" print(name.__class__.__name__) # "str"
Similarly, for a list, you can check the class name like so:
numbers = [1, 2, 3, 4] print(type(numbers).__name__) # "list" print(numbers.__class__.__name__) # "list"
If you have a custom class, you can check the class name of its object instance like so:
class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("John Doe", 39) print(type(person).__name__) # "Person" print(person.__class__.__name__) # "Person"
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.