目標: 使用僅在特定上下文中有效的角色擴展abitrary類。使用面向對象的Python對象進行面向對象或精化
這工作:
# 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()
我的問題:
EDIT2:我寫了100行代碼,用於普通的Python類,使這項工作,但對於內置命令我加入250行並沒有視線完整的解決方案。
我無法爲內建對象創建自定義類,因爲我可以使用純Python類作爲link:A或link:B。 這是因爲編譯器把它們無處不在:
>>> test.__code__.co_consts
(None, 1, 2, 3, (3,), 3)
我不能做的代碼列表對象,因爲它們是內置的代碼替換。
這是我的問題,因爲我無法估計它:
什麼是我要尋找的對象內置使用包裝來取代他們,所以我可以添加的角色給他們的地方?
將一個C的擴展幫我修補屬性查找,所以我可以爲布爾
我需要編譯我自己的Python實現這一設想的工作角色?
還有其他解決方案嗎?
編輯1
這是我的使用情況之一:1 .successor.successor == 3
。 我想讓擁有不妨礙整個程序的小型域名變得簡單=保持類別苗條。
例如,我想讓數字可調用來創建lambda演算。
我想要苗條的類和特殊用例,我想通過角色擴展它們,以便我可以調用它們的自定義函數。 我最終在Data-Context-Interaction和麪向上下文的編程應該出來。
如果你想改變的文字創建的對象的類型;您可能需要進行動態源代碼重寫,例如,請參閱['codeblocks' implemented](http://mtomassoli.wordpress.com/2012/04/20/code-blocks-in-python/) – jfs 2013-02-19 13:17:22