0

I have an class with a function that returns another instance of that class. Because a lot of logic has already been built into that function, I'd like to use it during the constructor.

Here's an example of what I'm trying to do:

class Hello(object):
    def __init__(self,name):
        self.name = name
        if name == "Carol":
            # trying to change the object
            self = self.append_hello("nice to meet you")

    def say_hi(self):
        print "Hi, " + self.name

    def append_hello(self,string):
        # This function returns a "Hello" class instance
        return HelloObject(self.name + " " + string)

And what the output looks like:

>>> h1 = Hello("Eric")
>>> h1.say_hi()
Hi, Eric
>>> h2 = h1.append_hello("how are you?")
>>> h2.say_hi()
Hi, Eric how are you?
>>> h1.say_hi()
Hi, Eric

But when I run:

>>> h3 = Hello("Carol")
>>> h3.say_hi()

I get Hi, Carol when I'd like for the object to be different and get Hi, Carol nice to meet you.

There are obvious ways to change the example so it does what I want. But I'd like to be able to use a function like append_hello() for more complicated cases. Any ideas?

eric chiang
  • 2,575
  • 2
  • 20
  • 23

2 Answers2

1

You can do this by defining __new__ instead of __init__.

For details, see Python's use of __new__ and __init__?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

This looks like it could be vulnerable for infinite recursion. If the naive test for "Carol" is removed or altered it could continue calling and creating new objects.

Furthermore, I believe you meant to write self = self.append_hello("nice to meet you")

As written, it would make more sense to have a greeting field as a member of the class. Then there is no need to are combine name and greeting and returned as new object. If your desire is immutable objects look up example for copy-on-write patterns.

Ben L
  • 1,449
  • 1
  • 16
  • 32