Python中的多态和构造函数行为
我在研究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);
不过,我不太明白在函数定义initializeFromVector
中,变量vector.values
是怎么设置的。
我觉得很奇怪,Python解释器怎么能访问vector.values
,因为在程序中并没有手动设置这个值,而且我也觉得values
并不是某种内置变量。
这算不算是可变类的一个例子呢?我一直觉得这种行为很奇怪。
1 个回答
4
其实很简单:initializeFromVector
这个函数需要一个类型为vector
的参数,然后它会查找这个vector
里的values
成员。这个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)