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.
Related
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
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
Say I have the classes in module.py
class A():
INPUTS = {}
def __init__():
self.inputs = do_something(self.INPUTS)
class B(A):
INPUTS = function_with_external_API_call()
def something_to_test():
pass # do stuff
In my unit tests (using pytest) I want to have an instance of B so that I can test B.something_to_test(). However importing the class B triggers function_with_external_API_call().
This solution works but it seems like a bad solution.
with requests_mock.mock() as m:
m.get(
'https://url.com',
json={'data': [{'id': '1'}]}
)
from module import B
How do I mock the function call so that I can import the class B and replace INPUTS with a mocked value?
I don't really understand fully what you try to do but INPUTS is in your case a class attribute. If you want INPUTS to be modified & called, I think it would be simpler to do like:
class A(object):
def __init__(self, mookup=None):
self.INPUTS = mookup
class B(A):
def __init__(self):
super().__init__(self.function_to_call)
def function_to_call(self):
pass
If this does not answer your question, can you please add more precisions to your question?
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
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.
j cannot be seen by another class; however, I think you meant self.j, which can.
class A(object):
def __init__(self, x):
self.x = x
class B(object):
def __init__(self):
self.sum = 0
def addA(self, a):
self.sum += a.x
a = A(4)
b = B()
b.addA(a) # b.sum = 4
Using class inheritane it is very easy to "share" instance variables
example:
class A:
def __init__(self):
self.a = 10
def retb(self):
return self.b
class B(A):
def __init__(self):
A.__init__(self)
self.b = self.a
o = B()
print o.a
print o.b
print o.retb()
class foo():
def __init__(self)
self.var1 = 1
class bar():
def __init__(self):
print "foo var1"
f = foo()
b = bar()
In foo, I am doing something that produces "var1" being set to 1
In bar, I would like to access the contents of var1
How can I access var1 in the class instance f of foo from within the instance b of bar
Basically these classes are different wxframes. So for example in one window the user may be putting in input data, in the second window, it uses that input data to produce an output. In C++, I would have a pointer to the caller but I dont know how to access the caller in python.
As a general way for different pages in wxPython to access and edit the same information consider creating an instance of info class in your MainFrame (or whatever you've called it) class and then passing that instance onto any other pages it creates. For example:
class info():
def __init__(self):
self.info1 = 1
self.info2 = 'time'
print 'initialised'
class MainFrame():
def __init__(self):
a=info()
print a.info1
b=page1(a)
c=page2(a)
print a.info1
class page1():
def __init__(self, information):
self.info=information
self.info.info1=3
class page2():
def __init__(self, information):
self.info=information
print self.info.info1
t=MainFrame()
Output is:
initialised
1
3
3
info is only initialised once proving there is only one instance but page1 has changed the info1 varible to 3 and page2 has registered that change.
No one has provided a code example showing a way to do this without changing the init arguments. You could simply use a variable in the outer scope that defines the two classes. This won't work if one class is defined in a separate source file from the other however.
var1 = None
class foo():
def __init__(self)
self.var1 = var1 = 1
class bar():
def __init__(self):
print var1
f = foo()
b = bar()
Same as in any language.
class Foo(object):
def __init__(self):
self.x = 42
class Bar(object):
def __init__(self, foo):
print foo.x
a = Foo()
b = Bar(a)
Alternatively you could have a common base class from which both derived classes inherit the class variable var1. This way all instances of derived classes can have access to the variable.
Something like:
class foo():
def __init__(self)
self.var1 = 1
class bar():
def __init__(self, foo):
print foo.var1
f = foo()
b = bar(foo)
You should be able to pass around objects in Python just like you pass around pointers in c++.
Perhaps this was added to the language since this question was asked...
The global keyword will help.
x = 5
class Foo():
def foo_func(self):
global x # try commenting this out. that would mean foo_func()
# is creating its own x variable and assigning it a
# value of 3 instead of changing the value of global x
x = 3
class Bar():
def bar_func(self):
print(x)
def run():
bar = Bar() # create instance of Bar and call its
bar.bar_func() # function that will print the current value of x
foo = Foo() # init Foo class and call its function
foo.foo_func() # which will add 3 to the global x variable
bar.bar_func() # call Bar's function again confirming the global
# x variable was changed
if __name__ == '__main__':
run()