vraj
vraj

Reputation: 41

Calling variable in one class file to another file in python3

Hi I'm a newbie in python programming. Please help me with this problem in python3:

pack.py

class one:

    def test(self):
        number = 100   ######I want to access this value and how?
        print('test')

class two:

    def sample(self):
        print('sample')

another.py

from pack import *

class three:

    def four(self):
        obj = one()
        print(obj.test())

###### I want to access the number value in this file and i don't know how #######

obj = three()
obj.four()

Upvotes: 1

Views: 6214

Answers (2)

dEBA M
dEBA M

Reputation: 507

Here is an alternative pack.py

class One:
    def __init__(self):
        self.number = 100

    def test(self):
        print('test')

class Two:
    def sample(self):
        print('Sample')

another.py

from pack import *

class Three:
    def four(self):
        self.obj = One().number
        return self.obj

three = Three().four()
print(three)

By what seems to be your approach, you were using classes to access variables. It is better to instantiate variables in a constructor ( init method in class One). Then import the class and access it in another class of another file.

Also, it is a good practice to name classes beginning with uppercase letters. There are more possible ways but hope it helps.

Upvotes: 3

laundmo
laundmo

Reputation: 338

number needs to be in a global scope, that means outside of a function definition (it shouldn't be indented)

if the variable is inside a function it is impossible to get it in another file

pack.py

number = 100
def test():
   test.other_number = 999 # here we assigne a variable to the function object.
   print("test")

another.py

import pack

pack.test()
print(pack.number)

print(test.other_number) # this only works if the function has been called once

Alternatively if you are using classes:

pack.py

class Someclass():
    other_number = 999 # here we define a class variable

    def __init__(self):
        self.number = 100 # here we set the number to be saved in the class

    def test(self):
        print(self.number) # here we print the number

another.py

import pack

somclass_instance = pack.Someclass() # we make a new instance of the class. this runs the code in __init__
somclass_instance.test() # here we call the test method of Someclass
print(somclass_instance.number) # and here we get the number

print(Someclass.other_number) # here we retrieve the class variable

Upvotes: 0

Related Questions