python 类调用不存在的方法_在Python中调用时是否可以创建不存在的方法?

Python首先检查是否存在具有该名称的属性,如果存在,则调用该属性。没有明确的方法可以提前检测是否调用此属性。在

以下是实现你想要的东西的巧妙方法:class Dispatcher(object):

def __init__(self, caller, name):

self.name = name

self.caller = caller

def __call__(self, *a, **ka):

print('Call on Dispatcher registered!',

'Will create method on',

self.caller.__class__.__name__,

'now.')

setattr(self.caller, self.name, self.mock)

return getattr(self.caller, self.name)(*a, **ka)

@classmethod

def mock(cls, *a, **ka):

return 'Some default value for newly created methods.'

class MyClass(object):

def __getattr__(self, attr):

return Dispatcher(self, attr)

instance = MyClass()

print(instance.new_method, '\n')

print(instance.new_method(), '\n')

print(instance.new_method(), '\n')

print(instance.other_method)

输出:

^{pr2}$

尽管此解决方案很全面,但每次尝试访问不存在的属性时,它都会返回Dispatcher的新实例。在

如果调用Dispatcher实例(例如Dispatcher(self, attr)()),它将把mock作为一个名为attr的新方法,作为第一个参数传递给构造函数。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值