【发布时间】:2017-10-22 05:04:24
【问题描述】:
背景
我希望使用元类来添加基于原始类的辅助方法。如果我希望添加的方法使用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 的一部分?
【问题讨论】:
标签: python class metaprogramming