I was reading up on multiple constructors Polymorphism in Python. I came across this 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);
However, I don’t understand how the variable vector.values was set in the function definition of initializeFromVector.
I find it weird how the Python interpreter is able to access vector.values even though its not set manually in the program, nor I think values is a built-in variable of some kind.
Is this an example of mutable class? I always thought this behavior was weird.
It’s very simple, really:
initializeFromVectortakes an argument of typevectorand looks up itsvaluesmember. This must have been set previously whenvectorwas constructed.As a simpler example: