Usage of getattr() in python

1.getattr() is a built-in function in python that gets the value of an attribute in an object

2.getattr(obj,name[,default]) where obj is the object name, name is an attribute in the object, and must be a string.

3. Differences between the two expressions

First, getattr(obj,"_attr")
Second, getattr (obj, "" + attr)
The first can only access the _attr attribute, while the second can access all underlined attributes

>>> class Student:  # Define Classes
	def __init__(self,name,identity,age):
		self._name = name
		self._identity = identity
		self.age = age
	def __getitem__(self,item):
		if isinstance(item,str):
			return getattr(self,"_item")
>>> st=Student("Huang Lei",1323010212,12)  # instantiation
>>> st["age"]
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    st["age"]
  File "<pyshell#49>", line 8, in __getitem__
    return getattr(self,"_item")
AttributeError: 'Student' object has no attribute '_item'

This way, only the'_item'property can be accessed.Underlined attributes or not.For example:

>>> st["name"]
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    st["name"]
  File "<pyshell#60>", line 8, in __getitem__
    return getattr(self,"_item")
AttributeError: 'Student' object has no attribute '_item'

>>> class Student:
	def __init__(self,name,identity,age):
		self._name = name
		self._identity = identity
		self.age = age
	def __getitem__(self,item):
		if isinstance(item,str):
			return getattr(self,"_" + item)
>>> st=Student("Huang Lei",1323010212,12)
>>> st["age"]
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    st["age"]
  File "<pyshell#54>", line 8, in __getitem__
    return getattr(self,"_" + item)
AttributeError: 'Student' object has no attribute '_age'
Although this step was unsuccessful, it was clear that the difference between the two was an underscore.

>>> st["name"]
'Huang Lei'
>>> s=["Huang Lei",1323010212,12]

name is defined with an underline, so that's how you can access underlined attributes.



Keywords: Attribute Python

Added by TheIceman5 on Mon, 24 Feb 2020 18:49:46 +0200