在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 中国大陆许可协议进行许可。

posted @   kingwzun  阅读(8234)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起