An example of using meta-class is the implementation of JavaScript protocol in Python.
This code defines __getattr__
for the Prototype
Class to view the class attribute prototype
when the Prototype instance .prototype
is called.
(if name=='prototype':
)
So I was concerned that the call to getattr
in (2) does not have return
.But why does the cls.prototype
return?
return getattr(self.__class__,name)
Why not?
#!/usr/bin/env python
## -*-coding:utf-8-*-
classPrototypeStore (dict):
""" US>" Class for storing values for x.prototype.XXX"
def__setattr__(self, name, value):
self[name] = value
def__getattr__(self, name):
return self [ name ]
classPrototypeMeta(type):
""" Prototype Metaclass (called when generating classes) "
def__new__(metacls, cls_name, bases, attrs):
cls = type.__new__(metacls, cls_name, bases, attrs)
cls.prototype=PrototypeStore()
return cls
classPrototype (object):
__metacclass__=PrototypeMeta
def__getattr__(self, name): #(1)
if name == 'prototype':
getattr(self.__class__,name)#(2)
else:
try:
getattr(object,name)
exceptAttributeError:
return self.__class__.prototype [name]
class TestClass (Prototype):
def__init__(self):
pass
The person who wrote the original code does not seem to understand that __getattr__
is invoked only when an undefined attribute is accessed.If you understand this, you will notice two strange things:
Therefore, neither getattr()
requires a return, and does not go through this code path in the first place.
Incidentally, .prototype
is set with the PrototypeStore instantiated when the definition of class TestClass(Prototype):...
is executed.
I think it's very simple to say, "If you can't find an attribute, I'll look for it from .prototype
.If I were to rewrite it, it would be as follows:
class Prototype (object):
__metacclass__=PrototypeMeta
def__getattr__(self, name):
return self.prototype [name]
Snakefoot: A similar method is _getattribute__
.This is called unconditionally regardless of whether the attribute is defined or undefined.The person who wrote the original code may have confused it with this method.Everyone is confused, so I think the author of Python who gave almost the same name is also responsible.
I don't really understand JavaScript's Prototype, so I may have overlooked something, but please refer to it.
© 2024 OneMinuteCode. All rights reserved.