为一个类声明多个构造函数的简洁方法是什么?
例如,假设我有一个 Item
类。创建项目的一种方法(例如是)
item = Item(product_id, name, description,price)
另一种方法可以做同样的事情
item = Item(otherItem)
然后另一种方法来做到这一点..也许在某些情况下我没有价格所以我想通过
item = Item(product_id, name,description)
还有一种情况可能是
item = Item(product_id,price)
我的另一个问题是:
有一些私有(private)变量可能会在运行时初始化。
假设我有一些随机变量 itemCount
,我想在内部跟踪它。
我如何声明我不必将其置于初始化模式,而是在运行时的某个位置...... 我可以做类似的事情
self._count +=1
谢谢
最佳答案
提供多个构造函数的两种最常见的方法是:
这是一个 example taken from the standard library显示如何 collections.OrderedDict使用类方法来实现 fromkeys() 作为备用类构造函数:
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self
作为另一种常见方法的示例,这里有一个 factory function used in symtable.py在标准库中:
class SymbolTableFactory:
def __init__(self):
self.__memo = weakref.WeakValueDictionary()
def new(self, table, filename):
if table.type == _symtable.TYPE_FUNCTION:
return Function(table, filename)
if table.type == _symtable.TYPE_CLASS:
return Class(table, filename)
return SymbolTable(table, filename)
关于Python:声明构造函数的灵活方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8129014/