我正在阅读 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/