Building useful classes


#1



In the code why do i only pass "self" as the argument and not x,y,z.

I passed the exercise but logically am trying to understand, why passing those arguments give me an error?


class Point3D(object):
    def __init__(self,x,y,z):
        self.x=x;
        self.y=y;
        self.z=z;
    
    def __repr__(self):
        return "(%d, %d, %d)" % (self.x, self.y, self.z)
        
my_point=Point3D(1,2,3)
print my_point


#2

Because x, y and z are member variables of the instance, to which self is the context reference. The context in any call is the caller, namely the owner object, or instance upon which the call is made.

instance.method()  =>  self.members
  owner                  context

Context and scope are difficult to distinguish one against the other. It takes some thinking.

I simplify it by thinking of scope in black and white terms. A chain that reaches from a function all the way up to the global namespace.

 > foobar = "foobar again, really?"
 > def foo(): 
..     def bar(): 
..         def really(): 
..             print (foobar) 
..         really() 
..     bar() 
..     
 > foo()
 foobar again, really?
 >

Notice that the innermost function searched up the entire scope chain to the find the variable, foobar. Vital importance to visualize this chain. Then scope is dealt with and there is no mystery. Scope is one of environment.

Context is objective. The object in focus is the context. It owns the current invocation of its methods. Think of a pop machine. My coin is the instance, and having defined that my instance now has access to all the methods that permit selection of the brand or flavor. Each option is a method. My instance can choose any one of them. A bit elementary, but a suitable starting metaphor.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.