Python... feeding an instance as an argument into a new instance.

Steve D'Aprano steve+python at pearwood.info
Sat Sep 2 20:45:03 EDT 2017


On Sun, 3 Sep 2017 08:34 am, Chris Roberts 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??

It has attributes and methods, same as any other instance of any other class.

I think you are overthinking it. Or perhaps underthinking it. In either case,
using generic nonsense classes like Foo and Bar adds no understanding.

Suppose you build an Engine class:


class Engine:
    def __init__(self, fuel, capacity):
        self.sparkplugs = [SparkPlug() for i in range(4)]
        ...
    def start(self):
        ...
    def stop(self):
        ...


So Engines have methods, and attributes such as capacity, the kind of fuel they
run on (petrol/gasoline, diesel or LPG), etc. Some attributes (such as the
sparkplugs) are themselves instances of another class.

Now we build a car out of other objects:


class Car:
    def __init__(self, colour, engine, chassis, seats, dashboard, wheels, 
                 brakes, parkingbrake, airbags, entertainment_system):
        self.colour = colour
        self.body = chassis.add_panels()
        self.engine = engine
        ...
    def drive(self):
        ...
    def reverse(self):
        ...
    def engage_parking_brake(self):
        ...


So Cars have methods, and attributes such as colour, engine, brakes, airbags,
etc. Some of those attributes are themselves made of instances of another
class.

In fact even "primitive" values such as ints, floats, lists, strings, tuples,
boolean flags etc are objects in Python. In Python, it is objects all the way
down: all values are objects.

Does this answer your question?

If not, I'm afraid I don't understand your question. Would you like to re-phrase
it and explain?

Thanks.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list