3
我正在閱讀多個構造函數Python中的Polymorphism。我遇到了這個code。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
是某種內置變量。
這是一個可變類的例子嗎?我一直認爲這種行爲很奇怪。
DOH!我知道丟失的東西很瑣碎! – garak 2013-02-20 13:37:55