setattr是什么,以及怎么用
时间: 2023-05-23 21:02:44 浏览: 48
setattr()是Python内置函数,用于设置对象的属性值。它的语法如下:
setattr(object, name, value)
其中,object是要设置属性的对象,name是属性名称,value是属性值。
例如,假设有一个类Person,我们可以通过setattr()设置其属性name的值:
class Person:
pass
person = Person()
setattr(person, 'name', 'Bob')
上述代码将person对象的name属性值设置为'Bob'。
相关问题
super().__setattr__是什么
`super().__setattr__` 是 Python 中的内置函数,用于在子类中对父类属性进行赋值操作。它可以调用父类的方法来设置属性,而不影响子类自身的属性。具体来说,它可以用于在子类中重载父类属性,或者在子类中增加新的属性。在调用 `super().__setattr__` 的时候,需要传入两个参数:第一个参数是子类的类名,第二个参数是属性名和属性值的键值对。例如:
```python
class Parent:
def __init__(self):
self._x = None
def get_x(self):
return self._x
def set_x(self, value):
self._x = value
class Child(Parent):
def __init__(self):
super().__init__()
self._y = None
def get_y(self):
return self._y
def set_y(self, value):
self._y = value
def set_x(self, value):
super().__setattr__('_x', value * 2)
```
在上面的代码中,`Child` 继承自 `Parent`,并在 `set_x` 方法中调用了 `super().__setattr__` 来设置 `_x` 属性的值。这样,当我们在子类中调用 `set_x` 方法时,实际上调用的是父类的 `set_x` 方法,并且将输入值乘以 2 后再进行赋值操作。
Python中 setattr()怎么使用
setattr() 是 Python 内置函数之一,用于设置对象的属性值。它的语法格式为:
setattr(object, name, value)
其中,object 表示要设置属性的对象,name 表示要设置的属性名,value 表示要设置的属性值。例如:
class Person:
name = "Tom"
p = Person()
setattr(p, "age", 18)
print(p.age) # 输出 18
这里我们通过 setattr() 函数为 Person 类的实例对象 p 添加了一个 age 属性,并将其值设置为 18。最后输出 p.age 的值,结果为 18。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)