Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Getattr ()() Function in Python

Explore Getattr ()() Function in Python with clear explanations, practical examples, and useful tips.

Table of Contents

This guide covers getattr ()() function in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.

The Getattr ()() Function Syntax in Python

getattr(doituong, tenthuoctinh[, macdinh])

Parameters of Getattr Function ()()

The getattr () function has 3 parameters:

  • Doituong: Object you want to check.
  • Tenthuoctinh: Name of the attribute to search.
  • Macdinh: Value returned if the property does not exist.

Note : getattr () function returns:

  • The value of the attribute if the object has an input attribute.
  • The default value if the object does not have a transfer attribute.
  • Exception AttributionError If no Attributes Are found and default values are not specified.

Example 1: How Does the Getattr ()() Function Work?

class Nhanvien:
 tuoi = 23
 ten = "QuachTinh"

nhanvien = Nhanvien()
print('So tuoi la:', getattr(nhanvien, "tuoi"))
print('So tuoi la:', nhanvien.tuoi)

Run the program, the result is:

So tuoi la: 23
So tuoi la: 23

Example 2: Default Value Parameter

class Nhanvien:
 tuoi = 23
 ten = "Adam"

nhanvien = Nhanvien()

# Khi truy?n giá tr? m?c ??nh 
 # Vi?t b?i TipsMake.com
print('Gioi tinh nhan vien la:', getattr(nhanvien, 'gioitinh', 'Nam'))

# Khi không truy?n giá tr? m?c ??nh
print('Gioi tinh nhan vien la:', getattr(nhanvien, 'gioitinh'))

Running the program results in:

Gioi tinh nhan vien la: Nam
AttributeError: 'Nhanvien' object has no attribute 'gioitinh'

The attribute is not in the Nhanvien Class , So when calling the getattr function with the default value of Male , the function will return 'Male', but if it does not pass this parameter as the code below, the program will generate an exception AttributeError.

Previous article: Function len () in Python

Next lesson: Python's globals () function

FAQ

What should I check before following these steps?

Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.

Why might the process not work?

Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.

Can I undo the changes if necessary?

That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.