python: create instance of class in another class (with generic example)
All attributes of an instance or class are accessed via self
which is passed as the first argument to all methods. That's why you've correctly got the method signature something_else(self, a, b)
as opposed to just something_else(a, b)
as you might with other languages. So you're looking for:
class BAR():
def __init__(self):
self.foo1 = FOO()
def something_else(self, a, b):
self.foo1.do_something(a, b)
Note that self isn't a keyword, it's just a paramater name like a
and b
, so you might for example be tempted to use this
instead if you're from a Java background... Don't though! there is a very strong convention to use self
for this purpose and you will make a lot of people (including yourself eventually) very angry if you use anything else!
With regards to passing values I'm not sure what you mean, you can access them through instances such as foo1.an_attribute
or pass them as arguments to functions as in function(arg)
but you seem to have used both techniques in your example so I'm not sure what else you're after...
Edit
In response to @dwstein's comment, I'm not sure how it's done in VB but here's a how you pass arguments when creating an instance of a class.
If we look at your class:
class BAR():
def __init__(self):
self.foo1 = FOO()
We can change that to accept an argument baz by changing second line to def __init__(self, baz):
and then if we want we can make baz
an attribute of our new instance of BAR
by setting self.baz = baz
. Hope that helps.
In python you always have to use the "self" prefix when accessing members of your class instance. Try
class BAR():
def __init__(self):
self.foo1 = FOO()
def something_else(self, a, b):
self.foo1.do_something(a, b)