Home > Mobile >  how to access function and its variables define in python class in another python file
how to access function and its variables define in python class in another python file

Time:03-31

I have a python file with name file1.py class defines

File1.py
class A(object):
    def func1(self, a, b, c):
        # foo
    def func2(self, a, b, c):
         var1=a
         var2=b
     return 

I want to access the class A func2 and its variable in a python file name file2.py.

I tried this ---> from File1 import A But its not working as I am unable to access func2 variables

CodePudding user response:

You're never returning any vars from func2 nor are you adding them as class variables.

Try:

class A():
  def __init__:
    self.var1 = None
    self.var2 = None

  def func1(self, a, b, c):
    #foo

  def func2(self, a, b, c):
    self.var1 = a
    self.var2 = b

Now you should be able to create an A object in file2.py, use func2 on it and then access var1 and var2:

from file1 import A

obj = A()
obj.func2('var A', 'var B', 'var C')

print(f'This is var1: {obj.var1}\nAnd this is var2: {obj.var2}')

>>> This is var1: var A
>>> This is var2: var B

CodePudding user response:

Python, similar to other programin languages, has notion of scope. In this example you don't have access to var1 and var2, they have function scope, unless they will be returned form function func2. To make it working first modify File1.py

File1.py
class A(object):
    def func1(self, a, b, c):
        # foo
    def func2(self, a, b, c):
         var1=a
         var2=b
     return var1, var2 

Then create file2.py in the same directory where is File1.py and paste

from File1 import A

x, y = A().func2(1, 2, 3)

print(x, y)

When you run file2.py you should get output 1 and 2 on your stdout

CodePudding user response:

"""
you may use another class which would be singleton to register all variables
for example lets say RegisterClass

"""


# file1.py
"""  this is our file1   
we need to make sure our class A has access to RegisterClass 
later in a different file we will access to RegisterClass and 
get all parameters passed to RegisterClass 
Please keep in mind that we need a singleton class as in this example shows 

"""
class RegisterClass:
        def __new__(cls ):
            if not hasattr(cls, 'instance'):
                cls.registered=[]
                cls.instance = super(RegisterClass, cls).__new__(cls)


            return cls.instance

        def append_new( cls, var1, var2  ) :
            my_tuple = (var1, var2)
            cls.registered.append( my_tuple )

class A(object):
    def func1(self, a, b, c):
        ...

    def func2(self, a, b, c):
        var1 = a
        var2 = b
        r = RegisterClass()
        r.append_new( var1 , var2 )

"""  this is our file2      """
#file2.py
#from file1 import *

class B(object ):
    def lets_access(self):

        for item in RegisterClass().registered :
            print( "item1 : {} item2 : {} ".format( item[0] , item[1 ] ))

A().func2( "a" , "b" , "c")
A().func2( "x" , "b" , "t")
A().func2( "y" , "z" , "m")

# now it is time to see which variables were passed to
# our function in class A
B().lets_access()
  • Related