首页 > 解决方案 > __init__ 需要什么

问题描述

class Sink:
    def __init__(self, basin, nozzle):
        self.basin = basin
        self.nozzle = nozzle

为什么我们使用或需要__init__方法?为什么它与下面的代码不一样?

class Sink:
    self.basin = basin
    self.nozzle = nozzle

标签: python-3.xclass

解决方案


参考:micropyramid:init是contructor

init的功能是在类内部进行构造。那个网站解释了init的目的

init ” 是 python 类中的一种保留方法。它在面向对象的概念中被称为构造函数。当从类创建对象时调用此方法,它允许类初始化类的属性。

在类中使用init的示例:

class Animal(object):
      def __init__(self, atype, avoice):
          self.type = atype
          self.voice = avoice
      
      def set_type(self):
          #do something in here about type
          if type == "cat":
             return "cat is like walk"
          else:
             return self.type+"is like walk"

      def set_voice(self):
          #do something in here similar with def type

推荐阅读