我是靠谱客的博主 拉长外套,这篇文章主要介绍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的新方法,作为第一个参数传递给构造函数。在

最后

以上就是拉长外套最近收集整理的关于python 类调用不存在的方法_在Python中调用时是否可以创建不存在的方法?的全部内容,更多相关python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(131)

评论列表共有 0 条评论

立即
投稿
返回
顶部