python-3.x - __init__ 需要什么
问题描述
class Sink:
def __init__(self, basin, nozzle):
self.basin = basin
self.nozzle = nozzle
为什么我们使用或需要__init__
方法?为什么它与下面的代码不一样?
class Sink:
self.basin = basin
self.nozzle = nozzle
解决方案
参考: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
推荐阅读
- indexing - scipy 稀疏 A[:,0] = ndarray ValueError
- python - 在训练和测试数据集中拆分后在 tf.stack 中获取 Keyerror 0
- time-complexity - 关于平方根的时间复杂度问题
- java - 春豆有什么作用?
- javascript - vue 路由器使用模式哈希删除默认页面中的标签
- android - 2020 年我应该使用 SyncAdapter 还是 AlarmManager 与服务器同步关键数据?
- spring - 当字段之一为空时,JPQL 不返回任何结果
- javascript - 如何确保一批请求已准备就绪
- php - 如何在不安全的协议上设置 instagram 基本显示中的 redirect_uri
- java - 当两个列表的大小不同时,从两个列表中添加具有相同索引的元素的值