Calling variable in one class file to another file in python3 - python

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

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.

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

Related

How can i separate methods of a class in separate files?

Let's say we have this class:
Class example:
def __init__(self):
self.var = 23
How can i access this variable within a function in another file by importing it in the main file?
def my_func():
pass
In fact i want the "my_func()" to be a method of the "example" class but in a separate file.
The idea is to split your class into two classes that have no data of their own—only methods—so although you inherit them, you never have to call super() on them. This classes are called "mixins"
_example.py
class Mixin:
def my_func(self):
print(self._b)
example.py
import _example
class Example(_example.Mixin):
def __init__(self):
self._a = 1
self._b = 2
self._c = 3
Now you can do:
ex = Example()
ex.my_func() # This will print "2" on console.
You can check different aproaches here

invoking a class method inside the class itself

Hi everyone i wanna use a calculated value from a method of the class itself for the rest of the class methods but it must calculate once for all and i need to invoke method inside the class itself i write an example:
class something():
def __init__():
pass
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
# I need to calculate summation here once for all:
# how does the syntax look likes, which one of these are correct:
something.__sum(1, 2)
self.__sum(1, 2)
# If none of these are correct so what the correct form is?
# For example print calculated value here in this method:
def do_something_with_summation(self):
print(self.summation)
Something like this seems to be what you're looking for:
class Something:
def __init__(self):
self.__sum(1, 2)
def __sum(self, variable_1, variable_2):
self.summation = sum(variable_1, variable_2)
Not saying this is the ideal approach or anything, but you haven't really given us much to go off of.
In general, make sure self is the first argument in all class methods, and you can call that class method at any time using either self.method_name() if you are using it from within another class method or instance.method_name() if you're using it externally (where instance = Something()).
Assuming that you would receive variable1 and variable2 when you instantiate the class one solution could be:
class something():
def __init__(self, variable1, variable2):
self.summation = variable1 + variable2
def do_something_with_summation(self):
print(self.summation)
If instead you're creating variable1 and variable2 inside other methods, then you could make them class variables:
class Something():
def __init__(self):
#Put some initialization code here
def some_other_method(self):
self.variable1 = something
self.variable2 = something
def sum(self):
try:
self.summation = self.variable1 + self.variable2
except:
#Catch your exception here, for example in case some_other_method was not called yet
def do_something_with_summation(self):
print(self.summation)

Initialize variable if class method is run

I have a class, like
class D:
def __init__(self):
"""some variables"""
def foo(self):
"""generates lots of data"""
I would like to be able to store all of the data that foo creates within the instance of the class that foo is being called from. Almost like creating a new initialization variable, but only once the method is called. For if the user never calls foo, no need to have generated the data to begin with.
Thanks!
How about to make a flag which will say if data was already generated?
class D:
def __init__(self):
self.already_generated = False
"""some variables"""
def foo(self):
"""generates lots of data"""
if not already_generated:
self.generate()...
already_generated = True
def generate(self,...):
Not quite sure if this is what you're trying to do, but if you want a class method to generate data that can be accessed from that instance you can put it into a data structure that is a member of that class:
class D:
def __init__(self):
#class member variables here
self.fooArray = []
def foo(self):
#insert your data to self.fooArray here, eg:
for i in range(1, 10000):
self.fooArray.append(i)

Python: Changing variables in another class from another

I have two files like the following
file1.py
class A:
def method1:
a = 5
file2.py
class B
def method2:
from file1 import A
a = 10
Forget the logic, its just an example. I wish to manipulate the value of a in my code. When I do this it gives me an error saying
"global name a is not defined". How can I solve this problem. Any help will be appreciated
The way you defined a it is a local variable to that method. What you want is self.a...
file1.py
class A:
def method1:
self.a = 5
file2.py
from file1 import A
class B:
def method2:
objecta = A()
objecta.a = 10
But reading your comments, what you actually want is something different.
Class A:
def __init__(self):
self.a = 5
def logic(self):
do some stuff...
Class B:
def solve(self):
first = A()
first.logic()
second = A()
second.logic()
etc...
The point of doing it with classes is that you can make multiple instances of the class. The init function creates an object of that class based on your baseline- so each time you make an A object, it will start out with your original settings.

Access subclass variables from parent file

I am looking for a way to access a subclasses variables from the parent class which is instantiated in a different file. For example
basefile.py:
class A(object): #gets subclassed
var = 0 #place holder
def printTheVar(self):
print self.var
class B(object):
def buildAndCallA(self):
a = A()
a.printTheVar()
implementationfile.py:
from basefile import *
class A(A):
var = 10
if __name__ == '__main__':
b = B()
b.buildAndCallA()
When I run:
$ python implementationfile.py
I get 0. I want to get 10
When both parent class and implementation class are in the same file, this is obviously not a problem but I have a project structure which requires they not be:
somedir/
| basefile.py
| implementations/
| -- implementationA.py
| -- implementationB.py
| -- implementationC.py
I think that the abc module might help but my experiments with that have proven fruitless so far.
I'd suggest, if possible, you pass the class you want to use to the buildAndCallA method. So it should look something like this:
def buildAndCallA(self,cls):
a = cls()
a.printTheVar()
And then you can call it like this:
b.buildAndCallA(A)
Then it will use whatever version of the A class is in scope at the time it is called.
You could even set it up with a default parameter, so it will use the version of A in the base file by default, but you can still override it when necessary.
def buildAndCallA(self,cls=A):
a = cls()
a.printTheVar()
Then if you call b.buildAndCallA() with no parameter, it will construct an instance of the A class from the base file.
#James's answer got me most of the ways there. Here is a more global way to do it using three files for clarity (which is really how the project is organized anyways)
script.py:
if __name__ == '__main__':
if sys.argv[0] == 'useImplementation1'
import implementations.implementation1 as implementation
elif sys.argv[1] == 'useImplementation2':
import implementations.implementation2 as implementation
b = implementation.B(cls=implementation)
b.buildAndCallA()
basefile.py (notice the A = cls.A this is the key):
class A(object):
var = 0 #place holder
def printTheVar(self):
print self.var
class B(object):
def __init__(self,cls):
global A
A = cls.A
def buildAndCallA(self):
a = A()
a.printTheVar()
implementation1.py:
from basefile import *
class A(A):
var = 10

Categories