Python setattr() 方法
Python setattr() 方法用于为对象属性分配其值。
除了通过构造函数和对象函数为类变量赋值的方法外,此方法还为您提供了另一种赋值方法。
Syntax : setattr(obj, var, val)
Parameters :
- obj : Object whose which attribute is to be assigned.
- var : object attribute which has to be assigned.
- val : value with which variable is to be assigned.
Returns : None
示例 1:演示 setattr() 的工作原理
Python3
# Python code to demonstrate
# working of setattr()
# initializing class
class Gfg:
name = 'GeeksforGeeks'
# initializing object
obj = Gfg()
# printing object before setattr
print("Before setattr name : ", obj.name)
# using setattr to change name
setattr(obj, 'name', 'Geeks4Geeks')
# printing object after setattr
print("After setattr name : ", obj.name)
Python3
# Python code to demonstrate
# properties of setattr()
# initializing class
class Gfg:
name = 'GeeksforGeeks'
# initializing object
obj = Gfg()
# printing object before setattr
print("Before setattr name : ", str(obj.name))
# using setattr to assign None to name
setattr(obj, 'name', None)
# using setattr to initialize new attribute
setattr(obj, 'description', 'CS portal')
# printing object after setattr
print("After setattr name : " + str(obj.name))
print("After setattr description : ", str(obj.description))
Python3
# Turns a dictionary into a class
class Dict2Class(object):
def __init__(self, my_dict):
for key in my_dict:
setattr(self, key, my_dict[key])
# Driver Code
if __name__ == "__main__":
# Creating the dictionary
my_dict = {"Name": "Geeks",
"Rank": "1223",
"Subject": "Python"}
result = Dict2Class(my_dict)
# printing the result
print("After Converting Dictionary to Class : ")
print(result.Name, result.Rank, result.Subject)
print(type(result))
Python3
class Person:
def __init__(self):
self._name = None
def name(self):
print('name function called')
return self._name
# for read-only attribute
n = property(name, None)
p = Person()
setattr(p, 'n', 'rajav')
输出:
Before setattr name : GeeksforGeeks
After setattr name : Geeks4Geeks
Python setattr() 属性
- setattr() 可用于将 None 分配给任何对象属性。
- setattr() 可用于初始化新的对象属性。
示例 2:演示 setattr() 的属性
Python3
# Python code to demonstrate
# properties of setattr()
# initializing class
class Gfg:
name = 'GeeksforGeeks'
# initializing object
obj = Gfg()
# printing object before setattr
print("Before setattr name : ", str(obj.name))
# using setattr to assign None to name
setattr(obj, 'name', None)
# using setattr to initialize new attribute
setattr(obj, 'description', 'CS portal')
# printing object after setattr
print("After setattr name : " + str(obj.name))
print("After setattr description : ", str(obj.description))
输出:
Before setattr name : GeeksforGeeks
After setattr name : None
After setattr description : CS portal
示例 3: Python setattr() 字典
让我们以一个简单的字典“my_dict”为例,它有 Name、Rank 和 Subject 作为我的键,它们的对应值是 Geeks, 1223, Python。我们在这里调用一个函数Dict2Class ,它将我们的字典作为输入并将其转换为类。然后,我们使用 setattr()函数循环遍历我们的字典,将每个键作为属性添加到类中。
Python3
# Turns a dictionary into a class
class Dict2Class(object):
def __init__(self, my_dict):
for key in my_dict:
setattr(self, key, my_dict[key])
# Driver Code
if __name__ == "__main__":
# Creating the dictionary
my_dict = {"Name": "Geeks",
"Rank": "1223",
"Subject": "Python"}
result = Dict2Class(my_dict)
# printing the result
print("After Converting Dictionary to Class : ")
print(result.Name, result.Rank, result.Subject)
print(type(result))
输出:
After Converting Dictionary to Class :
Geeks 1223 Python
Python setattr() 异常
在这里,我们将创建对象的只读属性,如果我们尝试使用setattr()函数设置属性的值,则会出现异常。
Python3
class Person:
def __init__(self):
self._name = None
def name(self):
print('name function called')
return self._name
# for read-only attribute
n = property(name, None)
p = Person()
setattr(p, 'n', 'rajav')
输出:
---> 16 setattr(p, 'n', 'rajav')
AttributeError: can't set attribute