0

How do I pass an instance of a class to the __init__ method of another class so that I can access it's variables?

eg:

class my_class:
    variable=0
    variabletwo=9

a=myclass()

How do I access the "variable" field of "a" from another class? I could write something like a.variable but that would only work for an object called "a".
i want to be able to provide the name of any object of the class"my_class" so that the variable field of that object can be accessed...
This might seem confusing so I'll do my best to provide an example.


like so:

class second_class:
    def __init__(self,external_variable):

when I create an instance of the "second_class" class I want to be able to pass "a" as the argument and be able to access the "variable" field of a. In this case the output should be 0 (zero).

2
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by mahela007
0

Within the method, the name of your instance is external_variable. So you simply write

class second_class:
    def __init__(self,external_variable):
        print(external_variable.variable) # prints 0
0

so will I be able to insert the name of any instance of my_class as the argument "external_variable"?

Say I've defined a instance of "my_class" like this
foo=my_class()

will something like

second_class(f)

output 0?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.