python - Python 中的多态性和构造函数行为

标签 python oop

我正在阅读 Python 中的多个构造函数多态性。我遇到了这个 code .

import sys, types, pprint

class Vector:
    """
    Demo of a class with multiple signatures for the constructor
    """
    def __init__(self, *args, **kwargs):

        if len(args) == 1:  foundOneArg = True;  theOnlyArg = args[0]
        else:               foundOneArg = False; theOnlyArg  = None

        if foundOneArg and isinstance(theOnlyArg, types.ListType):      
            self.initializeFromList(theOnlyArg)             
        elif foundOneArg and isinstance(theOnlyArg,Vector):
            self.initializeFromVector(theOnlyArg)           
        else:
            self.initializeFromArgs(*args)

        pprint.pprint(self.values)  # for debugging only

    def initializeFromList(self, argList):
        self.values = [x for x in argList]

    def initializeFromVector(self, vector):
        self.values = [x for x in vector.values]

    def initializeFromArgs(self, *args):
        self.values = [x for x in args]
#------------ end of class definition ---------------------

v = Vector(1,2,3) 
v = Vector([4,5,6]) 
q = Vector(v);

但是,我不明白initializeFromVector 的函数定义中如何设置变量vector.values

我觉得 Python 解释器如何能够访问 vector.values 很奇怪,即使它不是在程序中手动设置的,我也不认为 values 是一个内置的-在某种变量中。

这是一个可变类的例子吗?我一直认为这种行为很奇怪。

最佳答案

这非常简单,真的:initializeFromVector 接受一个类型为vector 的参数并查找它的values 成员。这必须在构建 vector 时预先设置。

举个简单的例子:

from copy import copy

class Set(object):
    def __init__(self, other=None):
        """Initialize; optionally copy the elements of another Set."""
        self.elements = set()
        if other is not None:
            self.elements = copy(other.elements)

关于python - Python 中的多态性和构造函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14981108/

相关文章:

Python、PyTables - 利用内核内搜索

python - Pandas 数据框中值的组合

c# - 抽象和封装有何不同?

java - 如何从另一个类访问和更改 JTextArea

oop - 类数据在内部传递好还是直接访问好?

Javascript OOP特权方法以私有(private)参数作为输入访问私有(private)方法

来自 postgresql 数据库的 Python 格式日期字符串

python - celery 任务优先级

python - 属性错误: 'ColumnTransformer' object has no attribute '_name_to_fitted_passthrough'

php - 与 Symfony 表单的关注点分离