![多个构造函数:Python方式?[重复],第1张 多个构造函数:Python方式?[重复],第1张](/aiimages/%E5%A4%9A%E4%B8%AA%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%EF%BC%9APython%E6%96%B9%E5%BC%8F%EF%BC%9F%5B%E9%87%8D%E5%A4%8D%5D.png)
您不能在中使用多个具有相同名称的方法
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中的默认值。⚠看这里。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)