Python:声明构造函数的灵活方式

标签 python constructor

为一个类声明多个构造函数的简洁方法是什么?

例如,假设我有一个 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

谢谢

最佳答案

提供多个构造函数的两种最常见的方法是:

  1. class methods
  2. factory functions

这是一个 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/

相关文章:

python - 字典创建中的可选字典项

C++ 模板限制成员构造函数

java - 使用 null 或默认构造函数初始化对象之间的区别

c++ - 在 C++ 中没有静态构造函数的理由是什么?

c++ - 是否可以在声明它的头文件中提供构造函数的定义?

python - 密码保护特定的 Jupyter 笔记本

python - 如何在已经包含 python 3.7.5 的 Ubuntu 19.10 上安装 python 3.6.5?

python - 如何解决Django和Postgresql的“关系{tableName}的列{columnName}不存在”

python - Unicode解码错误: 'ascii' codec can't decode byte 0xc3 in position 1286: ordinal not in range(128)

C++ 类在类构造上构造成员吗?