Search code examples
python-3.xclassmethodsattributes

How to access an attribute specified inside class scope, but not function scope in python?


i want to assign the value my_str to a variable my_out_of_scope_var2 that's defined inside a class A, but outside every method of that function. It feels pretty bad practice, but for the sake of a short question, let's assume i can not change the way it is implemented, because of legacy code.

class A:    
    def __init__(self, my_str):
        self.var1 = my_str
           
    def get_var1(self):
        return self.var1
    
    my_out_of_scope_var2 = ''

    # Ways NOT to do it
#     my_out_of_scope_var2 = bar             ----> not working, because bar is unknown here
#     my_out_of_scope_var2 = get_var1        ----> will assign the function >get_var1< to my_out_of_scope_var2
#     my_out_of_scope_var2 = self.var1       ----> does not work because self is unknown in this scope
#     my_out_of_scope_var2 = self.get_var1() ----> also does not work because self is unknown here

What i'm trying to achieve is this:

Foo = A('bar')
Foo.my_out_of_scope_var2

and the output not being '' but rather 'bar'.

How would i achieve that in a nice way in this kind of messy bad practice? I thought about using __call__ or __init__, decorators like @property or functions, but i just can't get to it.


Solution

  • You can set it in __init__ by referencing it through the class.

    class A:    
        def __init__(self, my_str):
            self.var1 = my_str
            A.my_out_of_scope_var = my_str
          
        def get_var1(self):
            return self.var1
        
        my_out_of_scope_var2 = ''