私信  •  关注

Matias Cicero

Matias Cicero 最近创建的主题
Matias Cicero 最近回复了
7 年前
回复了 Matias Cicero 创建的主题 » Python初始化时改变实例的属性

您需要明确声明接受 name 参数,然后需要显式更新相应的属性:

class Sensor():
    def __init__(self, name='pressure'):
        self.name = name

注意我正在使用 'pressure' 作为 名称 如果使用者不提供参数:

a = Sensor()
print(a.name) # 'pressure'

b = Sensor(name='sensor')
print(b.name) # 'sensor'

名称

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) # 70
print(d.active)      # True