2 posts tagged “python”
前回の続き.
これでいけた.
class Proxy:
def __init__(self, obj):
self.__dict__['_obj'] = objdef __getattr__(self, name):
return getattr(self._obj, name)def __setattr__(self, name, value):
setattr(self._obj, name, value)
a = Proxy(10)
str(a) #=> '10'
repr(a) #=> '10'
a + 3 #=> 13
long(a) #=> 10Lb = Proxy([])
b.append(10)
b.append(20)
b.pop() #=> 20
repr(b) #=> '[10]'
len(b) #=> 1class A(object):
def __len__(self):
return 3
c = Proxy(A())
len(c) #=> 3
Proxy(10) + 3 とかも効くのは凄い.
というか 6.5 章でズバリ解説されていた (死亡).
古い形式の class って推奨していいのかなー.
べ,別に GAE やら何とかのために Python やってるんじゃないんだからね!! ///
Python クックブック 9.1 章 (weaving) を試していて困った/疑問を持った話.
とりあえず 9.1 章のような継承 (name-mangling) は考えずに,再現する最小のコードをば.
class Proxy(object):
def __init__(self, obj):
object.__setattr__(self, 'obj', obj)def __getattribute__(self, name):
return object.__getattribute__(self, 'obj').__getattribute__(name)
すると,こんな感じで動く.
a = Proxy(10)
str(a) #=> '<__main__.Proxy object at 0x677d0>'
repr(a) #=> '<__main__.Proxy object at 0x677d0>'
a.__str__() #=> '10'
a.__repr__() #=> '10'
ううむ,若干期待と異なる挙動を見せる (全て '10' が返って欲しい).
更に.
b = Proxy([])
b.append(10)
b.pop() #=> 10
repr(b) #=> '<__main__.Proxy object at 0x67910>'
b.__repr__() #=> '[]'
len(b) #=> TypeError: object of type 'Proxy' has no len()
b.__len__() #-> 0
hasattr(b, '__len__') #=> True
うは,__len__ がある (見える) のに len 使えないのかー><
別に,組み込みオブジェクトを使ったからというわけではなく,通常のオブジェクトを使っても同じ挙動を見せる.
class A(object):
def __len__(self):
return 3c = A()
len(c) #=> 3d = Proxy(c)
len(d) #=> TypeError: object of type 'Proxy' has no len()
d.__len__() #=> 3
hasattr(d, '__len__') #=> True
単に __len__ の有無を見ているわけじゃなさそうだなぁ.
ちなみに,9.1 章に載っている inspect を用いたコードだと,組み込みオジェクトの殆どのメソッドを ismethod で inspect できずに b.append すらも失敗する.
これだったら普通に SynchronizeList とか欲しいなぁ.