stackingnauledge
stackingnauledge

Reputation: 29

Changing instance attribute from another class method

Is it possible to do this without using global variable? Is this considered a good coding practice or should I avoid it?

class ClassA:
    def __init__(self, array):
        self.array = array
    
    def method_a(self, scale):
        self.array = list(map(lambda x: x * scale, self.array))
        
class ClassB:
    def __init__(self):
        pass
    
    def method_b(self):
        '''it throws an error when im not using global variable defined in main:'''
        if len(instance_a.array) > 5:
            instance_a.method_a(10)
        
def main():
    global instance_a
    array_ = [1,2,3,3,6,5]
    instance_a = ClassA(array_)
    instance_b = ClassB()
    instance_b.method_b()

EDIT: just assigned array_

Upvotes: 0

Views: 562

Answers (2)

user12181582
user12181582

Reputation:

You should never need to do that. Also, I cant see where array_ is defined, which should raise an UnboundLocalError. Anyway, you will never production code expressed like that.

Upvotes: 0

rhurwitz
rhurwitz

Reputation: 2737

Instead of declaring instance_a as a global, you can pass the local instance as a parameter to method_b. Generally speaking, globals are to be avoided since the narrower the scope of a variable the easier it is debug should the need arise.

Example:

class ClassA:
    def __init__(self, array):
        self.array = array
    
    def method_a(self, scale):
        self.array *= scale
        
class ClassB:
    def __init__(self):
        pass
    
    def method_b(self, instance_a):
        if len(instance_a.array) > 5:
            instance_a.method_a(10)
        
def main():
    instance_a = ClassA(array_)
    instance_b = ClassB()
    instance_b.method_b(instance_a)

Upvotes: 2

Related Questions