2

I have the following code segment :

class A:
    def __init__(self):
        self.state = 'CHAT'

    def method1(self):
        self.state = 'SEND'

    def printer(self):
        print self.state


class B(A):
    def method2(self):
        self.method1()
        print self.state

ob_B = B()
ob_A = A()
ob_B.method2()
ob_A.printer()

This gives me the output :

SEND
CHAT

I want it to print :

SEND
SEND

That is, when B.method2 is modifying self.state by calling self.method1, I want it to modify the already existing value of self.state = 'CHAT' in A's instance. How can I do this?

3
  • 1
    You have instance attributes, and those are specific to the instances. You are not actually calling ob_B.method2. Commented Apr 26, 2013 at 10:21
  • That is my problem. I want self.state to be a class variable, and then have it initialized when an object of A is created. Commented Apr 26, 2013 at 10:24
  • @segfolt thanks for the edit. missing out () was a typo. Commented Apr 26, 2013 at 10:25

3 Answers 3

5

The instance is passed as the first argument to each of your methods, so self is the instance. You are setting instance attributes and not class variables.

class A:

    def __init__(self):
        A.state = 'CHAT'

    def method1(self):
        A.state = 'SEND'

    def printer(self):
        print A.state


class B(A):
    def method2(self):
        self.method1()
        print B.state

ob_B = B()
ob_A = A()
ob_B.method2()
ob_A.printer()

SEND
SEND
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This does it nicely. :) But just being inquisitive, say self.state is an instance variable. Is their a way to access it from class B?
@IndradhanushGupta Yes, it's part of the instance so it doesn't matter which class you are in unless you have overridden it in B, you just access it like self.x,
0
ob_B = B()
ob_A = A()
ob_B.method2()
ob_A.printer()

You need to call ob_B.method2() -- without the parentheses that statement is just a reference to the function and doesn't actually call it.

2 Comments

That doesn't change anything to the current problem.
Don't worry that was just a typo, his output matches up when you fix this
0

You can call the printer() method by using object of B so that you will get the updated value.

ob_B = B()
ob_A = A()
ob_B.method2()
ob_B.printer()

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.