Fire Method by predefined string!

Rick Johnson rantingrickjohnson at gmail.com
Sun Nov 17 23:23:11 CET 2013


On Sunday, November 17, 2013 3:46:16 PM UTC-6, Tamer Higazi wrote:

> class(object):
>     def Fire(self,param)
>         #possible ?!
>         self.__param():
>     def _DoSomething(self):
>         print 'I did it!'

1. First off your class declaration is not valid -- it needs
an identifier!

2. Never start a function or method with a lowercase letter.
Please read PEP8

3. I would advise using "self documenting names".

class Foo(object):
    def envokeMethodByName(self, name):
        ...

But what if the method takes arguments? >:)

class Foo(object):
    def envokeMethodByName(self, name, *args, **kw):
        getattr(self, name)(*args, **kw)

But what if want to restrict the methods?

class Foo(object):
    def __init__(self):
        self.allowedNames = [
            "play",
            "pause",
            "eject",
            ]
    def envokeMethodByName(self, name, *args, **kw):
        if name not in self.allowedNames:
            raise DontAbuseMyInterfaceMan("!")
        getattr(self, name)(*args, **kw)




More information about the Python-list mailing list