社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python初始化时改变实例的属性

Leo blubla • 5 年前 • 1183 次点击  

在初始化期间是否可以更改实例的属性?

E、 G以下代码。

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

Sensor1 = Sensor(name='pH') 

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54296
 
1183 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Polkaguy6000
Reply   •   1 楼
Polkaguy6000    6 年前

您需要给出一种方法来传递这些值并设置默认值。在您的示例中,只需添加默认值。

 class Sensor() :
     def __init__(self,name='pressure') :
          self.name = name
Carlos Gonzalez
Reply   •   2 楼
Carlos Gonzalez    6 年前

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

Sensor1 = Sensor(name='pH')

如果没有提供这个名字 pressure 但是,如果在初始化中指定了名称,则会将其设置为提供的名称。

Matias Cicero
Reply   •   3 楼
Matias Cicero    6 年前

您需要明确声明接受 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