> On Sep 2, 2017, at 3:34 PM, Chris Roberts <thecjg...@gmail.com> wrote:
> 
> Perhaps someone here could help me to get this into perspective. 
> Somehow when we start to feed an instance as the argument in a new instance. 
> my head explodes..
> in this case...
> a = Foo()
> b = Bar(a)
> So... 
> a is a 'Foo instance' with properties and methods. 
> b is a 'Bar instance'
> Since b is using the "a" instance as an argument?? 
> b=Bar(a)  has what?? 
> 

Unfortunately, the example that you are using serves to conflate a number of 
things.  For example, You have a class called Bar, a class variable inside the 
Foo class called bar, that variable has the value "Bar", in the __init__ method 
there is also self.bar.  I can see why you are confused.

But to try to answer you question, you are asking what happens when you do:  b 
= Bar(a)

That says, create an instance of the class Bar, pass in a as an argument, and 
assign the returned value to b.  

When that executes, the __init__ method of Bar runs 

class Bar(object):
   def __init__(self, arg):
       self.arg = arg
       self.Foo = Foo() #this calls and runs the Foo class again.

it assigns the value that is passed in (the instance of the Foo object), to the 
local parameter "arg".  The first assignment statement, says, copy that value 
into an instance variable called self.arg.  So, now self.arg which lives inside 
the new instance of the Bar class (called b), now has a reference to the a 
object that was created earlier.  That's all fine.  

In the next line, you are creating a new instance of the Foo class, and 
assigning the result to a different instance variable called self.Foo.  (This 
is also extremely confusing in terms of names.)

Bottom line, after running the code, a refers to an instance of the Foo object. 
 b now has two instance variables, which refer to two different instances of 
the Foo object.  The first one (self.arg) refers to the same instance as a.  
The second one refers to a second of a Foo object.  You can see this if you add 
print statements:

class Bar(object):
   def __init__(self, arg):
       self.arg = arg
       self.Foo = Foo() #this calls and runs the Foo class again.
       print('self.arg', self.arg)
       print('self.Foo', self.Foo)

If you also print out the value of a right after you create it, you will find 
that it matches the value of self.arg in b.  Two references to the same object.

Hope that helps,

Irv


-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to