【问题标题】:Creating variable in class or in __init__ in python3 [duplicate]在python3的类或__init__中创建变量[重复]
【发布时间】:2018-10-11 16:24:07
【问题描述】:

在类中创建变量并在__init__ 中为其赋值与直接在__init__ 中创建变量之间有什么区别?

例如:

示例 1:

# I create the var color outside __init__ and assigns a value to it inside __init__

class Car:
   color = ""
   def __init__(self):
      self.color = "green"

示例 2:

# I directly create the variable inside __init__ and not outside __init__ and just assign a value in __init__

class Car:
    def __init__(self, color):
        self.color = color

有影响吗?

【问题讨论】:

标签: python python-3.x class initialization member


【解决方案1】:

第一个示例有两个不同的color 属性:color = "" 创建一个 class 属性 如果实例没有自己的属性,将使用显示值。 self.color = "green" 显式创建一个 instance 属性,其值为 "green"

在您的第二个示例中,没有类属性,您使用__init__ 的参数而不是硬编码值来定义实例属性。

【讨论】:

    【解决方案2】:

    __init__是创建对象时用来初始化对象的构造函数。

    -> __init__(self): self.color='green'
    

    这将创建一个类变量,您将无法在创建对象时传递新值。

    ->__init__(self,color): self.color=color
    

    另一方面,上面的代码将允许您将颜色属性分配给您的对象。

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 2020-05-13
      • 2015-08-17
      相关资源
      最近更新 更多