A python object: It can be everything!

18 Jun 2009 Geng Wang project

The code is like this:

class unknown_obj(object):

    def __call__(self, *arg): return unknown_obj()

    def __getitem__(self, key): return unknown_obj()

    def __getattr__(self, name): return unknown_obj()

The three methods are: __call__ for function calls (*arg means arg is the argument list), __getitem__ for the visit to members using ‘[]’, such as a[3] and 3 is the key, __getattr__ just like we mentioned, for any visit to members using ‘.’. So almost every kind of codes is legal to an object like this. For example:

>»a = unknown_obj()

>»print a.b[123].c[‘abc’].d(456, ‘def’).e

<__main__.unknown_obj object at 0xb76b552c>

If we want to know exactly which member is called, we can modify the code above, like this:

class unknown_obj(object):

    def __call__(self, *arg):

        print arg

        return unknown_obj()

    def __getitem__(self, key):

        print key

        return unknown_obj()

    def __getattr__(self, name):

        print name

        return unknown_obj()

>»a = unknown_obj()

>»print a.b[123].c[‘abc’].d(456, ‘def’).e






(456, ‘def’)


<__main__.unknown_obj object at 0xb76b564c>

Such an object can be used for a COM simulation, so we don’t need to implement everything for every kinds of COM, and a call to a function can be output for further analyze.