社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Matias Cicero

Matias Cicero 最近创建的主题
Matias Cicero 最近回复了
6 年前
回复了 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