quas
quas

Reputation: 343

how to modify parent class variable with the child class and use in another child class in python

class A(object):
    __A = None
    def get_a(self):
        return self.__A
    def set_a(self, value):
        self.__A = value

class B(A):
    def method_b(self, value):
        self.set_a(value)

class C(A):
    def method_c(self)
         self.get_a()

Someone can to explain me how can i to catch installed value in method_b inside my 'C' class method?

P.S. In this variant i just getting nothing.

Upvotes: 2

Views: 11410

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55509

Python isn't Java; you don't need setters & getters here: just access the attributes directly.

There are three problems with your code.

  1. C.method_c() has no return statement, so it returns None.

  2. You are using __ name mangling when that's exactly what you don't want.

  3. In A.set_a() you want to set a class attribute, but your assignment instead creates an instance attribute which shadows the class attribute.

Here's a repaired version.

class A(object):
    _A = 'nothing'
    def get_a(self):
        return self._A
    def set_a(self, value):
        A._A = value

class B(A):
    def method_b(self, value):
        self.set_a(value)

class C(A):
    def method_c(self):
        return self.get_a()

b = B()
c = C()
print(c.method_c())
b.method_b(13)
print(c.method_c())

output

nothing
13

Here's a slightly more Pythonic version:

class A(object):
    _A = 'nothing'

class B(A):
    def method_b(self, value):
        A._A = value

class C(A):
    pass

b = B()
c = C()
print(c._A)
b.method_b(13)
print(c._A)

Upvotes: 6

Related Questions