内置python对象的面向主题或优化 [英] Subject Oriented or Refinements with builtin python objects
问题描述
目标: 用只在特定上下文中有效的角色来扩展任意类.
Goal: Extend abitrary classes with roles that are only valid in a certain context.
这有效:
# from https://github.com/niccokunzmann/wwp/blob/master/C_builtinTypes.py
from relative import roleOf, useRoles
@roleOf(int)
class NaturalNumber:
# int gets successor only in this module
@property
def successor(self):
return 1 + self
@roleOf(tuple)
@roleOf(list)
class MyList:
@property
def first(self):
return self[0]
@useRoles
def test():
# this is possible if we recompile the code objects
i = 1
print(type(i))
assert i.successor == 2
assert i.successor.successor == 3
assert isinstance(i, int) # EDIT3 works
# check for identity
t = (3,)
assert t.first == 3
l = list()
l.append(3)
assert l.first == 3 # this assertion fails
assert l.first == 2 + 1
if __name__ == '__main__':
test()
我的问题:
我为普通的python类编写了100行代码来完成这项工作,但对于内置函数,我添加了250行代码,因此看不到完整的解决方案.
I wrote 100 lines of code for usual python classes to make this work but for builtins I added 250 lines and there is no complete solution in sight.
我无法像使用纯python类一样为内置对象创建自定义类,如 link:A 或链接:B . 这是因为编译器将它们放置在各处:
I can not create custom classes for builtin objects as I can with pure python classes as link:A or link:B. This is because the compiler puts them everywhere:
>>> test.__code__.co_consts
(None, 1, 2, 3, (3,), 3)
我无法用列表替换代码对象,因为它们内置在代码中.
I can not do the replacement in code objects with lists because they are built in the code.
这些是我的问题,因为我无法估算:
These are my questions because I can not estimate it:
-
在哪里可以找到内置对象以将其替换为包装器,以便为它们添加角色?
What are the places I have to look for builtin objects to replace them with wrappers so I can add roles to them?
通过C扩展名可以帮助我修补属性查找,以便为布尔值扮演角色
would an C-extension help me patch the attribute lookup so I can make roles for booleans
我是否需要编译自己的python才能使此想法生效?
will I need to compile my own python to make this idea work?
还有其他解决方案吗?
编辑1
这是我的用例之一:1 .successor.successor == 3
.
我想使不影响整个程序的小域变得容易=使类保持苗条.
This is one of my Use-cases: 1 .successor.successor == 3
.
I want to make it easy to have small domains that do not interfer with the whole program = keep classes slim.
例如,我想使数字可调用以创建lambda演算.
For example I want to make numbers callable to create a lambda calculus.
我想拥有苗条的类,对于特殊的用例,我想通过角色扩展它们,以便可以在它们上调用自定义函数. 最后,应该出现在数据-上下文-交互和面向上下文的编程之间的东西.
I want to have slim classes and for special use cases I want to extend them by roles so I can call custom functions on them. I the end something between Data-Context-Interaction and Context-Oriented Programming should come out.
推荐答案
我认为您想研究Abstract Base Classes:
I think you want to look into Abstract Base Classes:
http://docs.python.org/3/library/abc.html
这篇关于内置python对象的面向主题或优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!