栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

多个构造函数:Python方式?[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多个构造函数:Python方式?[重复]

您不能在中使用多个具有相同名称的方法

Python
Java
不支持函数重载-与in不同。

使用默认参数或

**kwargs
*args
参数。

您可以使用

@staticmethod
@classmethod
装饰器制作静态方法或类方法,以返回类的实例,或添加其他构造函数。

我建议你这样做:

class F:    def __init__(self, timestamp=0, data=None, metadata=None):        self.timestamp = timestamp        self.data = list() if data is None else data        self.metadata = dict() if metadata is None else metadata    @classmethod    def from_file(cls, path):       _file = cls.get_file(path)       timestamp = _file.get_timestamp()       data = _file.get_data()       metadata = _file.get_metadata()   return cls(timestamp, data, metadata)    @classmethod    def from_metadata(cls, timestamp, data, metadata):        return cls(timestamp, data, metadata)    @staticmethod    def get_file(path):        # ...        pass

⚠永远不要将可变类型作为python中的默认值。⚠看这里。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614311.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号