What does hasattr() function do in Python?

PythonServer Side ProgrammingProgramming

The hasattr() method in Python

The hasattr() method returns true if an object has the given named attribute and false if it does not.

Syntax

The syntax of hasattr() method is −

hasattr(object, name)

The hasattr() is called by getattr() to check to see if AttributeError is to be raised or not.

The hasattr() method takes two parameters −

The hasattr() method returns −

True, if object has the given named attribute

False, if object has no given named attribute

Example

class Male:
    age = 21
    name = 'x'
x = Male()
print('Male has age?:', hasattr(x, 'age'))
print('Male has salary?:', hasattr(x, 'salary'))

Output

This gives the output

('Male has age?:', True)
('Male has salary?:', False)


raja
Published on 12-Jan-2018 18:05:48
Advertisements