在Python实现多个构造函数/构造方法
原因:
python只允许一个init 函数构造类
法1:将init的参数改为不定长参数:
方法思路:
将__init__ 的参数改为不定长参数,
然后在__init__ 中通过判断参数的数量,进行不同的操作
class Rect: __length = 0 __width = 0 # 使用不定长参数 def __init__(self, *x): if len(x) == 1: self.__length = x[0] self.__width = x[0] elif len(x) == 2: self.__length = x[0] self.__width = x[1] def e(self): return self.__width * self.__length # 正常使用 t = Rect(1) print(t.e()) t = Rect(2, 4) print(t.e())
法2: @classmethod 装饰器重载构造函数(推荐)
@classmethod 装饰器允许在不实例化类的情况下访问该函数。此类方法可以由类本身及其实例访问。当用于重载时,此类函数称为工厂方法。
我们可以使用他来实现 Python 中构造函数重载,使用看代码吧。
class Rect: __length = 0 __width = 0 def __init__(self, l, w): self.__length = l self.__width = w @classmethod def initsec(self, l): # 记得返回self return self(l, l) def e(self): return self.__width * self.__length #使用方法和init不同 t = Rect.initsec(1) print(t.e()) t = Rect(2, 4) print(t.e())
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/16335499.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步