Python setattr()方法 用于为对象属性指定其值。
null
除了通过构造函数和对象函数为类变量赋值之外,这个方法还提供了另一种赋值方法。
语法: setattr(对象、变量、值)
参数:
- obj: 要指定其属性的对象。
- 变量: 必须指定的对象属性。
- 瓦尔: 要分配给变量的值。
返回: 没有一个
例1:D 演示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) |
输出:
Before setattr name : GeeksforGeeksAfter setattr name : Geeks4Geeks
Python setattr()属性
- setattr()可用于不为任何对象属性赋值。
- setattr()可用于初始化新的对象属性。
例2:D 演示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 : GeeksforGeeksAfter setattr name : NoneAfter setattr description : CS portal
示例3:Python setattr()dict
让我们以一个简单的字典“my_dict”为例,它以名称、等级和主题作为键,它们的对应值为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<class '__main__.Dict2Class'>
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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END