3

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

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);

但是,我不明白如何vector.valuesinitializeFromVector.

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

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

4

1 回答 1

4

真的很简单: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)
于 2013-02-20T13:34:19.713 回答