2

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'

2
  • You shouldn't access it. If you wrote B, don't use name-mangling to hide the attribute. If someone else wrote B, then maybe there's a reason they are hiding access. Commented May 16, 2020 at 12:44
  • The current error is because you are passing an instance of A to a function that expects an instance of B. Commented May 16, 2020 at 12:45

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.