How to access class attributes within a class variable?

Viewed 109

I want to reference a class attribute from class variable but it gives me error 'self is not defined'

class Test:
    def __init__(self, val):
        self.val = val

    data = self.val

    def main(self):
        print(self.data)
1 Answers

When you say data = self.val outside __init__, you are defining a class variable, not an instance variable. This line affects all objects of type Test. However, self is not recognized in this scope.

If you want val to update all instances of this class,

class Test:
    data = None
    def __init__(self, val):
        self.val = val
        Test.data = self.val

In this case,

test1 = Test(1)
print(test1.data) # prints 1
print(Test.data)  # prints 1
test2 = Test(2)
print(test1.data) # prints 2
print(test2.data) # prints 2
print(Test.data)  # prints 2
Related