For a.py:
class a():
def __init__(self,var = 0):
self.var = var
def p(self):
print(self.var)
For b.py:
import a
a.var=2
o=a()
o.p()
What I want is: 2.
But it shows: 0.
When I import the module, ta, I want to use add_all_ta_features in this module, which use other class in this module. Meanwhile, I want to change the variable in other class, but the result is still the same.
Could anyone help me with that? Thank you.
For a.py:
class a():
def __init__(self,var = 0):
self.var = var
def p(self):
print(self.var)
For b.py
import a
ob=a.a(2)
## Or you can do
## ob=a.a()
## ob.var=2
p=ob.p()
In this case, your output will be 2, What exactly is happening that your class name and the python module name are the same. In here you have just imported the module, but when you create an object of any class you have to use the class name using the above method or by these methods.
## Method 2
from a import a
ob=a(2)
## Or you can do
## ob=a()
## ob.var=2
p=ob.p()
or
## Method 3
import a as obj
ob=obj.a(2)
## Or you can do
## ob=obj.a()
## ob.var=2
p=ob.p()
Go ahead and initialise a
b.py:
import a
an_a = a()
a.var = 23 #set whatever you want
print(a.var)
Related
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
I'm trying to access variables I created in one function inside another module in Python to plot a graph however, Python can't find them.
Heres some example code:
class1:
def method1
var1 = []
var2 = []
#Do something with var1 and var2
print var1
print var2
return var1,var2
sample = class1()
sample.method1
here is class 2
from class1 import *
class number2:
sample.method1()
This does as intended and prints var1 and var2 but I can't call var1 or var2 inside class number 2
FIXED EDIT:
Incase anyone else has this issue, I fixed it by importing this above class two
from Module1 import Class1,sample
And then inside class2
var1,var2 = smaple.method1()
The code you posted is full of syntax errors as Francesco sayed in his comment. Perhaps you could paste the correct one.
You don't import from a class but from a package or a module. Plus you don't "call" a variable unless it's a callable.
In your case you could just have :
file1.py :
class class1:
def __init__(self): # In your class's code, self is the current instance (= this for othe languages, it's always the first parameter.)
self.var = 0
def method1(self):
print(self.var)
sample = class1()
file2.py :
from file1 import class1, sample
class class2(class1):
def method2(self):
self.var += 1
print(self.var)
v = class2() # create an instance of class2 that inherits from class1
v.method1() # calls method inherited from class1 that prints the var instance variable
sample.method1() # same
print(v.var) # You can also access it from outside the class definition.
v.var += 2 # You also can modify it.
print(v.var)
v.method2() # Increment the variable, then print it.
v.method2() # same.
sample.method1() # Print var from sample.
#sample.method2() <--- not possible because sample is an instance of class1 and not of class2
Note that to have method1() in class2, class2 must inherit from class1. But you can still import variables from other packages/modules.
Note also that var is unique for each instance of the class.
I'm new with Python and I'm trying to use classes to program using objects as I do with C++.
I wrote 3 .py files.
a.py
from b import *
class A:
def __init__(self):
self.m_tName = "A"
def test(self):
tB = B()
tB.do( self )
b.py
from a import *
class B:
def __init__(self):
self.m_tName = "B"
def do(self, tA ):
if not isinstance( tA, A ):
print ( "invalid parameter" )
print( "OK" )
demo.py:
from a import *
if __name__ == "__main__":
tA = A()
tA.test()
As you can see I want to use a A() object to call the member function test() that creates a B() object and call the member function do() that uses a A() object.
So in B::do() I want to check the parameters using the built-in function isinstance(). But python tells me that there's a NameError: global name 'A' is not defined.
The A() class file is imported at the top of the b.py file.
Does anyone know what I'm doing wrong here ?
As pointed in some comment, circular dependencies are not well handled if imported in the form from a import A.
In short, the problem with ... import * is that is causes the local scope to have all its declarations overridden, in effect making the identification of from which module (in your case) a class comes from. This causes exactly what you are facing.
Changing the import statement in the following way, together with a classified reference to a.A, produces OK as output.
import a
class B:
def __init__(self):
self.m_tName = "B"
def do(self, tA ):
print tA
if not isinstance( tA, a.A ):
print ( "invalid parameter" )
print( "OK" )
As a bit of additional information, this has already been discussed in Why is "import *" bad?. I would point in special to this answer: https://stackoverflow.com/a/2454460/1540197.
**Edit:**This article explain the import confusion.
You have a circular dependancy, a.py and b.py import each other.
You could move either import statement inside the method where it is used.
So b.py would become:
class A:
def __init__(self):
self.m_tName = "A"
def test(self):
from b import B
tB = B()
tB.do( self )
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.
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