Wednesday, March 21, 2012

I just wanted to see what would happen...

>>> class Foo:
...    def __init__(self):
...       self.info = "I am a foo"
... 
>>> foo = Foo()
>>> foo.info
'I am a foo'
>>> class Bar(foo):
...    def __init__(self):
...       self.info2 = "This should be interesting"
... 
Traceback (most recent call last):
  File "", line 1, in
TypeError: Error when calling the metaclass bases
    __init__() takes exactly 1 argument (4 given)
>>> 

6 comments:

  1. Sorry, I'm a Python newbie, but was there something you expected to happen when Python tried to evaluate the class statement with the expression list containing a foo instance instead of the Foo class object?

    ReplyDelete
  2. Well, at the outset, let it be said that I was just messing around... :)

    Honestly, I just got curious to see what Python would do. It's certainly not something you would expect to work, or indeed make sense.

    I wondered whether it would be possible to have a situation where you subclassed an already initialised object, overriding its methods but inheriting the initialised values of the object. For example, it seemed like you might be able to have a situation where you have

    GenericObject and at some point discover that it could really be considered an instance of some MoreSpecificObject. Rather than re-initialising things, you might want to at runtime do a class-change to account for that.

    No, it doesn't make sense entirely. Yes, there are other ways to do it. I just believe in messing around...

    ReplyDelete
  3. Hi, can I ask what do you mean other ways to do it?

    Suddenly I got interested in the idea that you have already an initialized object that you wanna subclass then rather re-initializing things you wanna change in on runtime? Can you have an example on the other ways that you can do this?

    ReplyDelete
  4. Well, one way to do it would be to have subclasses that take an instance of the parent class in their init method. Another would be to have some kind of factory method on either the parent or the sub class to build them.

    I've just discovered how you would do it if you wanted to though... you can override the __new__ and __init__ methods and pretty much do what you want. :) I'm about to post something on using some fancy footwork here to avoid resorting to factory methods.

    ReplyDelete
  5. I've just remembered my original desire for this. I have some underlying data object, with lots of useful methods. I want to create a higher-level object, but it still makes sense to be able to make many of the same calls as are already implemented on the data object. I wanted to create a new object which inherited the methods on the data object, but had some higher-level methods and state of its own also.

    ReplyDelete
  6. For such a use case, I'd probably lean toward writing a wrapper for the higher-order class, containing its own methods and passing calls down to the wrapped data object.

    ReplyDelete