__getattribute__
yönteminin sonsuz döngüden kaçınılması için dikkatle yazılması gerekir. Örneğin:Python: sonsuz döngüden kaçınmak için __getattribute__
class A:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
return self.x
>>> a = A()
>>> a.x # infinite looop
RuntimeError: maximum recursion depth exceeded while calling a Python object
class B:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
return self.__dict__[x]
>>> b = B()
>>> b.x # infinite looop
RuntimeError: maximum recursion depth exceeded while calling a Python object
Dolayısıyla biz bu şekilde yöntem yazmak gerekir: object.__getattribute__
yöntem çalışır neden
class C:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
# 1. error
# AttributeError: type object 'object' has no attribute '__getattr__'
# return object.__getattr__(self, x)
# 2. works
return object.__getattribute__(self, x)
# 3. works too
# return super().__getattribute__(x)
Sorum şu? object
nereden __getattribute__
yöntemini alır? object
herhangi __getattribute__
yoksa, o zaman biz sadece sınıfın C
üzerinde ama süper sınıfın aracılığıyla aynı yöntemi çağırıyor. Neden, yöntemi süper sınıf yoluyla çağırmak sonsuz bir döngüye neden olmaz?
'__getattribute__' ve '__getattr__'' ye ihtiyacınız olduğundan emin misiniz? –
Evet, çünkü sınıfımda TÜM öznitelik getirilerini engellemem gerekiyor. Ama yapmasam bile, bunun neden böyle olduğunu tam olarak bilmek isterim. – treecoder
Peki ya * tüm * öznitelik erişimini engellemek zorunda ya da :-) –