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).

Recommended Answers

All 4 Replies

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

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?

second_class(foo)

Yeah... I mean second_class(foo)

Thanks for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.