The function hasattr () in Python

The hasattr () function in Python is used to check if the input object has the property you want to find.

The hasattr () function in Python is used to check if the input object has the property you want to find. How is the syntax of hasattr () function, what parameters does it have and how to use it? Invites you to read the track.

The syntax of hasattr () function in Python

 hasattr(doituong, tenthuoctinh) 

Parameters of hasattr () function :

The hasattr () function has 2 parameters:

  1. Doituong: object you want to check
  2. tenthuoctinh: name of the attribute to search

Note :

Function hasattr () returns:

  1. TRUE if the object has a transmission attribute.
  2. FALSE if the object has no transmission attribute.

Example: How does hasattr () function work?

 class Nhanvien: 
tuoi = 31
ten = 'QuachTinh'

nhanvien = Nhanvien()

print('Doi tuong Nhanvien co thuoc tinh tuoi khong?:', hasattr(nhanvien, 'tuoi'))
print('Doi tuong Nhanvien co thuoc tinh ten khong?:', hasattr(nhanvien, 'ten'))
print('Doi tuong Nhanvien co thuoc tinh luong khong?:', hasattr(nhanvien, 'luong'))

Run the program, the result is:

 Doi tuong Nhanvien co thuoc tinh tuoi khong?: True 
Doi tuong Nhanvien co thuoc tinh ten khong?: True
Doi tuong Nhanvien co thuoc tinh luong khong?: False

Previous lesson: Hex () function in Python

Next lesson: filter () function in Python

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile