def __init__(self, **opts):
时间: 2023-09-05 14:06:51 浏览: 87
build_opts
The `__init__` method is a special method in Python classes that is called when an object of that class is created. It is used to initialize the attributes of the object with default values or values provided by the user.
The `**opts` parameter in the `__init__` method is used to accept any number of keyword arguments provided by the caller. This is achieved by using the double asterisk (`**`) before the parameter name, which allows the caller to pass any number of keyword arguments in the form of `key=value` pairs.
For example, if we have a class `Person` with attributes `name`, `age`, and `gender`, we can define its `__init__` method to accept these attributes as keyword arguments:
```
class Person:
def __init__(self, **opts):
self.name = opts.get('name', '')
self.age = opts.get('age', 0)
self.gender = opts.get('gender', '')
```
In this example, we use the `get` method of the `opts` dictionary to retrieve the values of the `name`, `age`, and `gender` attributes, with default values of empty string (`''`) for `name` and `gender`, and zero (`0`) for `age`, if the caller does not provide them.
Using this method, the caller can create a `Person` object and set its attributes with keyword arguments, like this:
```
person = Person(name='Alice', age=25, gender='female')
```
This creates a `Person` object with `name` set to `'Alice'`, `age` set to `25`, and `gender` set to `'female'`. If the caller does not provide any keyword arguments, the default values will be used.
阅读全文