0

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.

2
  • 2
    Why are you using global if you want the variables to be different? Commented Feb 6, 2013 at 4:44
  • It seems like your methods need to have a self in there somewhere as they're not decorated with staticmethod or anything of the like... Commented Feb 6, 2013 at 4:55

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.