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"
Hope you found this post useful. It was published . Please show your love and support by sharing this post.