我正在阅读 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.values
在 initializeFromVector
.
我发现 Python 解释器如何能够访问它很奇怪,vector.values
即使它没有在程序中手动设置,我也不认为values
它是某种内置变量。
这是可变类的一个例子吗?我一直觉得这种行为很奇怪。