米脂
您需要明确声明您接受一个name参数,然后您需要明确更新适当的属性:class Sensor(): def __init__(self, name='pressure'): self.name = name请注意,我将'pressure'用作name参数的默认值,以防消费者不提供它:a = Sensor()print(a.name) # 'pressure'b = Sensor(name='sensor')print(b.name) # 'sensor'name 也可以作为位置参数提供:c = Sensor('some_name')print(c.name) # 'some_name'更通用的方法还有一种更通用的方法(如果用例需要的话),它涉及动态创建属性:class Sensor(): def __init__(self, **kwargs): for attr, value in kwargs.items(): setattr(self, attr, value)然后你可以做这样的事情:d = Sensor(name='foo', temperature=70, active=True)print(d.name) # 'foo'print(d.temperature) # 70print(d.active) # True