Reputation: 1
I'm trying to write a module that contains multiple classes. I want the same variable name in every class but want the values to be different. So that every definition will use the variable defined in the top of its own class.
For example:
class assign():
global a , b
a = 1
b = 2
def aa(x):
return a*x
class assign1():
global a, b
a = 5
b = 10
def aa(x) :
return a*x
This Produces:
print(assign.aa(3))
=15
print(assign1.aa(3))
=15
The global values aren't switch between the different classes and I would like them to be.
Upvotes: 0
Views: 56
Reputation: 310287
Interesting -- I've never seen global
in the class namespace before ... Basically what happens is when you create your class, you add a
and b
to the global namespace. Then, in your method call, you pick up a
from the global namespace (because there is no local variable a
). What you probably wanted is:
#while we're at it, get in the habit of inheriting from object
# It just makes things nicer ...
class assign(object):
a = 1
b = 2
def aa(self,x):
return self.a*x
class assign1(object):
a = 5
b = 10
def aa(self,x) :
return self.a*x
Now, when you call the aa
method, python will first look for an attribute a
on the instance. When it's not found on the instance, the class will be checked (and used since the classes both have an a
attribute).
Upvotes: 1