Kavin R M
Kavin R M

Reputation: 23

Accessing private variable of one class in another class in python

How can I access the private variable 'number' of class B in another class A, in the below code?

    class A:
            def write(self):
                print("hi")

            'It should print the private variable number in class B'
            def check(self):
                print(B.get_number(self))'error occurs here'

        class B:
            def __init__(self,num):
                self.__number = num 

            'accessor method'
            def get_number(self):
                return self.__number

        #driver code        
        obj = B(100)
        a = A()
        a.write()
        a.check()

The error message I get is 'A' object has no attribute '_B__number'

Upvotes: 2

Views: 2056

Answers (2)

Tobias
Tobias

Reputation: 1371

In your code, you are trying to read the __number field of the object a (which is of class A) instead of obj (which is of class B).

The instruction a.check() is basically translated to A.check(self=a). This means that inside the check()-method you are then calling B.get_number(self=a), and the get_number()-method therefore tries to return a.__number (which does not exist).

What you might want to do is this:

    class A:
        def check(self, other):
            print(B.get_number(other)) # <- NOT "self"!

    class B:
        ...

    obj = B(100)
    a = A()
    a.write()
    a.check(obj)

Upvotes: 3

Gabio
Gabio

Reputation: 9484

You can do it by changing check method to receive B object.

Try:

class A:
    def write(self):
        print("hi")

    def check(self,b):
        print(b.get_number())

class B:
    def __init__(self, num):
        self.__number = num

    'accessor method'

    def get_number(self):
        return self.__number

obj = B(100)
a = A()
a.write()
a.check(obj)

Upvotes: 4

Related Questions