-1

So here is some example code

class hi(object)
    def __init__(self):

        self.answer = 'hi'

    def change(self):

        self.answer ='bye'
        print self.answer

    def printer(self):

        print self.answer

class goodbye(object):

    def bye(self):

        hi().change() 

goodbye().bye()
hi().printer()

When i run this code i output

'bye'
'hi'

I want it to output

'bye'
'bye'

Is there a way to do this while still initializing self.answer to hi or will this cause it to always re-initialize to 'hi' no matter what i do afterwards?

RayGunV
  • 17
  • 6
  • 2
    `goodbye.bye` is working on a **completely different** `hi` instance to the one that you're calling `printer` on! And they're *instance attributes*, not *class attributes*. – jonrsharpe Jun 04 '15 at 15:57
  • Look up the `Singleton` pattern – sirfz Jun 04 '15 at 15:58
  • possible duplicate of [Is there a simple, elegant way to define Singletons in Python?](http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python) – sirfz Jun 04 '15 at 15:58
  • you posted your expected output, but it's unclear why you want that behaviour. – Karoly Horvath Jun 04 '15 at 15:58
  • 1
    The short answer is to make `answer` a *class attribute* and `change` a *class method*, but it's not clear why you want to do this at all - could you provide a less abstract example? – jonrsharpe Jun 04 '15 at 16:07

1 Answers1

1

You are using instance attributes not class attributes as jonrsharpe pointed out.

Try something like this:

class hi(object):
    answer = 'hi'

    def __init__(self):
        pass

    @classmethod
    def change(cls):
        cls.answer ='bye'
        print cls.answer

    def printer(self):
        print self.answer

class goodbye(object):

    def bye(self):
        hi.change() 

goodbye().bye()
hi().printer()

Here answer is now a class attribute and change() is a classmethod

camz
  • 605
  • 3
  • 15