super().__setattr__
时间: 2023-11-04 13:04:36 浏览: 145
`super().__setattr__()` is a built-in Python function that can be used to call the `__setattr__()` method of the parent class in a subclass. It is commonly used when you want to add some additional functionality to the `__setattr__()` method of the parent class without completely overriding it.
Here's an example:
```python
class MyClass:
def __setattr__(self, name, value):
print(f"Setting {name} to {value}")
super().__setattr__(name, value)
class MySubclass(MyClass):
def __setattr__(self, name, value):
print(f"Adding extra functionality for {name} = {value}")
super().__setattr__(name, value.upper())
```
In this example, `MySubclass` is a subclass of `MyClass`. It overrides the `__setattr__()` method of its parent class to add some extra functionality. However, it still wants to call the `__setattr__()` method of the parent class to handle the actual setting of the attribute.
To do this, it uses `super().__setattr__(name, value.upper())` to call the `__setattr__()` method of the parent class and pass in the modified value. This allows it to add its own functionality while still preserving the functionality of the parent class.
阅读全文