2013-02-20 16 views
3

我正在閱讀多個構造函數Python中的Polymorphism。我遇到了這個codePython中的多態和構造函數行爲

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是某種內置變量。

這是一個可變類的例子嗎?我一直認爲這種行爲很奇怪。

回答

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) 
+0

DOH!我知道丟失的東西很瑣碎! – garak 2013-02-20 13:37:55