jhpjhll 发表于 2022-10-21 17:43:02

一个类中可以有两个__init__()么,为什么呢

class EXCEL:
    def __init__(self):
      self.name = ""
      self.colname = ""
      self.type = ""


    def __init__(self,name,col_name,type):
      self.name = str(name)
      self.colname = str(col_name)
      self.type = str(type)
求问下,为什么这么写呢

tommyyu 发表于 2022-10-21 18:06:52

第二个会把第一个覆盖掉

jackz007 发表于 2022-10-21 18:11:02

本帖最后由 jackz007 于 2022-10-21 18:23 编辑

      写 2 个同名的 __init__(),那是 C 语言构造函数重载的套路,在 Python 语言中,有更好的解决方案。
      设置缺省参数就可以了,如果调用的时候不写参数,就使用参数的缺省值
class EXCEL:
    def __init__(self , name = '' , colname = '' , type = ''):
      self . name = name
      self . colname = col_name
      self . type = type
页: [1]
查看完整版本: 一个类中可以有两个__init__()么,为什么呢