
Python hasattr() - How to check if the object or instance has an attribute or property
The hasattr()
checks if the object or instance has an attribute. It is a built-in function in Python.
class User:
def __init__(self, name):
self.name = name
def buy(self):
print(self.name + ' is buying')
def sell(self):
print(self.name + ' is selling')
u = User(name='Josh')
if hasattr(u, 'name'):
print('name')
if hasattr(u, 'buy'):
print('buy')
if hasattr(u, 'do'):
print('do')
# name
# buy
do
is not printed because the user object doesn't have the do
attribute. You can get the attributes of an instance by __dir__()
.
class User:
def __init__(self, name):
self.name = name
def buy(self):
print(self.name + ' is buying')
def sell(self):
print(self.name + ' is selling')
u = User(name='Josh')
d = u.__dir__()
print(d)
# ['name', '__module__', '__init__', 'buy', 'sell', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
Comments
Powered by Markdown