背景
我希望使用元类来添加基于原始类的辅助方法。如果我想要添加的方法使用self.__attributeName
,由于名称修饰,会出现AttributeError
问题,但对于现有的相同方法则不会有问题。
代码示例
这里是一个简化的示例:
# Function to be added as a method of Test
def newfunction2(self):
"""Function identical to newfunction"""
print self.mouse
print self._dog
print self.__cat
class MetaTest(type):
"""Metaclass to process the original class and
add new methods based on the original class
"""
def __new__(meta, name, base, dct):
newclass = super(MetaTest, meta).__new__(
meta, name, base, dct
)
# Condition for adding newfunction2
if "newfunction" in dct:
print "Found newfunction!"
print "Add newfunction2!"
setattr(newclass, "newfunction2", newfunction2)
return newclass
# Class to be modified by MetaTest
class Test(object):
__metaclass__ = MetaTest
def __init__(self):
self.__cat = "cat"
self._dog = "dog"
self.mouse = "mouse"
def newfunction(self):
"""Function identical to newfunction2"""
print self.mouse
print self._dog
print self.__cat
T = Test()
T.newfunction()
T.newfunction2() # AttributeError: 'Test' object has no attribute '__cat'
问题
有没有一种方法可以添加newfunction2
,并且可以使用self.__cat
?
(不需要将self.__cat
重命名为self._cat
。)
或许更基本的问题是,为什么self.__cat
在两种情况下没有被同样地处理,因为newfunction2
现在是Test
的一部分了?