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
Related
I have designed a way to inherit from a class programmatically, so basically extending a class. It works pretty nicely. However, I need to pickle the class, and this is not possible as the extended class is defined within a function.
Here is a toy example for the extended class:
import pickle
class A():
pass
def extend_class(base_class):
class B(base_class):
def hello(self):
print('Yo!')
return B
extended_class = extend_class(A)
b = extended_class()
b.hello()
However if I do
pickle.dump(b, open('extended_class.pickle', 'w'))
this returns:
AttributeError: Can't pickle local object 'extend_class.<locals>.B'
Any workaround? I don't necessarely need to use my way to extend a class. Any other way would be acceptable, as long as I can pickle the class in the end.
You could declare a class in the global domain, then, declare it global in the factory function, and overwrite it.
It looks like a bit of a hack, and there might be a better way (maybe by injecting the class directly into the class dict), but nonetheless, here it is:
import pickle
class A:
pass
class _B:
pass
B = _B
def extend_class(base_class):
global B
class B(base_class):
def hello(self):
print('Yo!')
return B
if __name__ == '__main__':
extended_class = extend_class(A)
b = extended_class()
b.hello()
with open('tst.pickle', "wb") as f:
pickle.dump(b, f)
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 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'm writing Python scripts for Blender for a project, but I'm pretty new to the language. Something I am confused about is the usage of static variables. Here is the piece of code I am currently working on:
class panelToggle(bpy.types.Operator):
active = False
def invoke(self, context, event):
self.active = not self.active
return{'FINISHED'}
class OBJECT_OT_openConstraintPanel(panelToggle):
bl_label = "openConstraintPanel"
bl_idname = "openConstraintPanel"
The idea is that the second class should inherit the active variable and the invoke method from the first, so that calling OBJECT_OT_openConstraintPanel.invoke() changes OBJECT_OT_openConstraintPanel.active. Using self as I did above won't work however, and neither does using panelToggle instead. Any idea of how I go about this?
use type(self) for access to class attributes
>>> class A(object):
var = 2
def write(self):
print type(self).var
>>> class B(A):
pass
>>> B().write()
2
>>> B.var = 3
>>> B().write()
3
>>> A().write()
2
You can access active through the class it belongs to:
if panelToggle.active:
# do something
If you want to access the class variable from a method, you could write:
def am_i_active(self):
""" This method will access the right *class* variable by
looking at its own class type first.
"""
if self.__class__.active:
print 'Yes, sir!'
else:
print 'Nope.'
A working example can be found here: http://gist.github.com/522619
The self variable (named self by convention) is the current instance of the class, implicitly passed but explicitely recieved.
class A(object):
answer = 42
def add(self, a, b):
""" ``self`` is received explicitely. """
return A.answer + a + b
a = A()
print a.add(1, 2) # ``The instance -- ``a`` -- is passed implicitely.``
# => 45
print a.answer
# => print 42