Create instance of class in another class (with generic example)

Viewed 78417

I'm learning python via book and internet and I'm stuck on a class issue.

2 questions:

  1. How do I create an instance of one class in another (separate) class?
  2. How do I pass variables between the class and the nested(?) class?

When I try to create an instance of a class within another (separate) class, i'm able to do so within a method. Here's the code:

import os

class FOO():
    def __init__(self):
        self.values = [2, 4, 6, 8]

    def do_something(self, x, y):
        os.system("clear")
        z = self.values[x] * self.values[y]
        print "%r * %r = %r" % (self.values[x], self.values[y], z)


class BAR():
    def __init__(self):
        pass

    def something_else(self, a, b):
        foo1 = FOO()
        foo1.do_something(a, b)

bar = BAR()
bar.something_else(1, 2)

Will this, however, allow me to access the FOO class and it's information in other BAR methods? If so, how?

I tried the following and got an error:

import os

class FOO():
    def __init__(self):
        self.values = [2, 4, 6, 8]

    def do_something(self, x, y):
        os.system("clear")
        z = self.values[x] * self.values[y]
        print "%r * %r = %r" % (self.values[x], self.values[y], z)


class BAR():
    def __init__(self):
        foo1 = FOO()

    def something_else(self, a, b):
        foo1.do_something(a, b)

bar = BAR()
bar.something_else(1, 2)

Here is the error:

Traceback (most recent call last):
File "cwic.py", line 22, in <module>
bar.something_else(1, 2)
File "cwic.py", line 19, in something_else
foo1.do_something(a, b)
NameError: global name 'foo1' is not defined

I get the same error when I used:

def __init__(self):
    self.foo1 = FOO()

Also, how should I pass the 'values' from one class to the other?

Please let me know if my general approach and/or syntax are wrong.

5 Answers

If you don't create a def __init__(self): method for a class, you have to initialize the class as: eg:

class XYZ:
    def foo(self):
        ....
        ....
r1 = XYZ()

and to access the method you have to write r1.foo() But as you have created a init method you have to access the foo function as self.foo() which is equal to r1.foo() so in your code, instead of foo1.do_something(), it should be self.foo1.do_something()

Related