using variables in class functions in another class (python)

10,300
class check1:
    def helloworld(self):
        self.j = 5

check_instance=check1()
print (hasattr(check_instance,'j'))  #False -- j hasn't been set on check_instance yet
check_instance.helloworld()          #add j attribute to check_instance
print(check_instance.j)  #prints 5

but you don't need a method to assign a new attribute to a class instance...

check_instance.k=6  #this works just fine.

Now you can use check_instance.j (or check_instance.k) just like you would use any other variable.

This may seems a little bit like magic until you learn that:

check_instance.helloworld()

is completely equivalent to:

check1.helloworld(check_instance)

(If you think about it a little bit, that explains what the self parameter is).

I'm not completely sure what you're trying to achieve here -- There are also class variables which are shared by all instances of the class...

class Foo(object):
    #define foolist at the class level 
    #(not at the instance level as self.foolist would be defined in a method)
    foolist=[]  

A=Foo()
B=Foo()

A.foolist.append("bar")
print (B.foolist)  # ["bar"]
print (A.foolist is B.foolist) #True -- A and B are sharing the same foolist variable.
Share:
10,300
afroze
Author by

afroze

Updated on June 05, 2022

Comments

  • afroze
    afroze almost 2 years

    I want to use the variables i have declared inside a function in one class, in another class.

    For example i want to use the variable "j" in another class. Is it possible? (I read somewhere that it might have something to do with instance variables but fully couldn't understand the concept).

    class check1:
        def helloworld(self):
            j = 5