如何在 Python 中定义后缀函数?
How do I define a postfix function in Python?
我知道如果您创建自己的对象,您可以在该对象上定义自己的方法。
my_object_instance.mymethod()
我也知道您可以使用 infix 包定义中缀函数。
obj1 |func| obj2
我想要的是能够定义一个接受后缀表示法中现有类型的函数。
例如给定一个列表 l
我们可能想检查它是否已排序。定义一个典型的函数可能会给我们
if is_sorted(l): #dosomething
但如果写成
可能会更地道
if l.is_sorted(): #dosomething
这是否可以不创建自定义类型?
Python 通常不允许对内置类型进行猴子修补,因为常见的内置类型不是用 Python(而是 C)编写的,并且不允许 class要修改的字典。您必须根据需要子class 它们来添加方法。
正确的方法是继承,通过继承 list
并添加新功能来创建自定义类型。 Monkeypatching 不是 Python 的强项。但是既然你特地问了:
Is this possible without creating a custom type?
的立场,Python不允许。但是由于实现中没有任何内容是真正只读的,您可以通过修改 class 字典来近似计算结果。
>>> def is_sorted(my_list):
... return sorted(my_list) == my_list
...
>>> import gc
>>> gc.get_referents(list.__dict__)[0]['is_sorted'] = is_sorted
>>> [1,2,3].is_sorted()
True
>>> [1,3,2].is_sorted()
False
新的 "method" 将出现在 vars(list)
中,名称将出现在 dir([])
中,并且它也会 available/usable 在创建的实例上 在 应用猴子补丁之前。
此方法使用 garbage collector interface to obtain, via the class ,对基础字典的引用。通过引用计数进行垃圾收集是一个 CPython 实现细节。可以这么说,这是 dangerous/fragile 并且您不应该在任何严肃的代码中使用它。
如果您喜欢这种功能,您可能会喜欢 ruby 作为一种编程语言。
我知道如果您创建自己的对象,您可以在该对象上定义自己的方法。
my_object_instance.mymethod()
我也知道您可以使用 infix 包定义中缀函数。
obj1 |func| obj2
我想要的是能够定义一个接受后缀表示法中现有类型的函数。
例如给定一个列表 l
我们可能想检查它是否已排序。定义一个典型的函数可能会给我们
if is_sorted(l): #dosomething
但如果写成
可能会更地道if l.is_sorted(): #dosomething
这是否可以不创建自定义类型?
Python 通常不允许对内置类型进行猴子修补,因为常见的内置类型不是用 Python(而是 C)编写的,并且不允许 class要修改的字典。您必须根据需要子class 它们来添加方法。
正确的方法是继承,通过继承 list
并添加新功能来创建自定义类型。 Monkeypatching 不是 Python 的强项。但是既然你特地问了:
Is this possible without creating a custom type?
>>> def is_sorted(my_list):
... return sorted(my_list) == my_list
...
>>> import gc
>>> gc.get_referents(list.__dict__)[0]['is_sorted'] = is_sorted
>>> [1,2,3].is_sorted()
True
>>> [1,3,2].is_sorted()
False
新的 "method" 将出现在 vars(list)
中,名称将出现在 dir([])
中,并且它也会 available/usable 在创建的实例上 在 应用猴子补丁之前。
此方法使用 garbage collector interface to obtain, via the class
如果您喜欢这种功能,您可能会喜欢 ruby 作为一种编程语言。