views:

41

answers:

3

is there a way to define a value within a class in the __init__ part, send it to some variable outside of the class without calling another function within the class?

like

class c:
     def __init__(self, a):
           self.a = a
           b = 4           # do something like this so that outside of class c, 
                           # b is set to 4 automatically for the entire program
                           # when i use class c

     def function(self):
         ...               # whatever. this doesnt matter

i have multiple classes that have different values for b. i could just make a list that tells the computer to change b, but i would rather set b within each class

+1  A: 

I'm not sure I understood the question correctly, but try adding this line into the __init__:

global b

Before assignment to b I mean. Like the first line of the function.

doublep
A: 

Basically, the answer is no. You can make a parent class that does the callback for you, then you won't need to think about it beyond passing the b value to the parent class constructor. But unless you want to use global variables (which is not a good idea), there is no way to return a value from a constructor that is not the object.

unholysampler
+1  A: 

Since globals are bad, try a class variable. (Is there any reason you can't?) For example:

class C(object):
    def __init__(self,a):
        self.a=a
        C.b=4

or, better yet:

class C(object):
    b=4
    def __init__(self,a):
        self.a=a

global, as doublep suggests, will bind to a variable global to the module. Since it's limited to the module namespace, it's not that bad an option.

outis