在类中生成动态方法
我想要一个具有动态方法的类。
从这些数组中:
prefix = ['android','iphone','blackberry']
method = ['AddToPush','DelFromPush','GetPushMessages']
我想创建一个类,例如:
class MobileManager(object)
def __init__(self):
self.mobileLib = MobileLib()
def androidAddToPush(self, args):
self.mobileLib.AddToPush(args, 'android')
def iphoneAddToPush(self, args):
self.mobileLib.AddToPush(args, 'iphone')
def blackberryAddToPush(self, args):
self.mobileLib.AddToPush(args, 'blackberry')
[...]
如何在运行时生成/创建这些方法?
I want to have a class with dynamic methods.
From these arrays:
prefix = ['android','iphone','blackberry']
method = ['AddToPush','DelFromPush','GetPushMessages']
I want to create a class like:
class MobileManager(object)
def __init__(self):
self.mobileLib = MobileLib()
def androidAddToPush(self, args):
self.mobileLib.AddToPush(args, 'android')
def iphoneAddToPush(self, args):
self.mobileLib.AddToPush(args, 'iphone')
def blackberryAddToPush(self, args):
self.mobileLib.AddToPush(args, 'blackberry')
[...]
How can I have these methods generated/created at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你的前缀/方法集是在初始化时定义的,你可以尝试这样的事情:
如果你的动态方法变得更加复杂,那么 lambda 很快就会受到限制。
If your set of prefixes/methods is defined at init time, you can try something like this:
If your dynamic methods get more complicated, the lambda will soon be limited, though.
或者为什么不继承
Or why not inherate
动态方法通常是错误的方法,会导致代码混乱。
在这里,我会这样做:
在您的管理器中:
现在,您可以编写
manager.android.add_to_push(args),而不是
。manager.mobileLib.add_to_push(args, 'android')
)如果您有平台变量,您甚至可以动态调度:
getattr(manager, platform).add_to_push(args)
。如果您希望 3 种类型的平台有不同的行为,您可以创建 Mobile 的子类(可能是 AndroidMobile、BlackberryMobile 和 iPhoneMobile)。
当一个新平台出现时(也许是windows7),如何更改代码来支持它是显而易见的。
Dynamic methods are often the wrong approach leading to confusing code.
Here, I'd do this:
And in your Manager:
Now, instead of
manager.mobileLib.add_to_push(args, 'android')
, you would writemanager.android.add_to_push(args)
.You can even dispatch dynamically if you have a platform variable:
getattr(manager, platform).add_to_push(args)
.If you want different behaviour for the 3 types of platform you can make subclasses of Mobile (perhaps AndroidMobile, BlackberryMobile and IPhoneMobile).
When a new platform appears (perhaps windows7) it's obvious how to change the code to support it.