我在Python 2.6中使用「新風格」類,並且在子類中遇到了__getattr__問題。python __getattr__ and __name__
如果子類實現像這樣......
def __getattr__(self, name):
if self.__folderDict.has_key(name):
if name == 'created':
return doSomethingSpecial(self.__folderDict[name])
return self.__folderDict[name]
else:
raise AttributeError()
爲什麼我的屬性例外被拋出一個參考__name__目前尚不清楚對我?
我的理解是__getattr__甚至不應該被調用,__name_應該由__getattribute__填充,因爲我使用新的樣式?
下面是一個更完整的例子...
class Base(object):
@staticmethod
def printMsg(msg, var):
print msg + str(var)
return
def printName(self):
Base.printMsg('#', self.__name__)
return
class Derived(Base):
def __getattr__(self, name):
if self.__testDict.has_key(name):
return self.__testDict[name]
else:
raise AttributeError()
__testDict = {'userid': 4098}
d = Derived()
print d.userid
d.printName()
結果是...
4098
Traceback (most recent call last):
File "D:/.../Scratch/scratch01.py", line 24, in <module>
d.printName()
File "D:/.../Scratch/scratch01.py", line 17, in __getattr__
raise AttributeError()
AttributeError
你可以顯示實際的調用代碼和追蹤? – bgporter 2012-03-17 15:49:20
同意以前的評論,你的信息不是很詳細和清晰,當他們想寫答案時,人們可能會感到困惑。但根據你對__getattr__和__getattribute__的理解,[這篇文章](http://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute-in-python)似乎對你有用。 – Reorx 2012-03-17 16:06:46
增加了另一個簡單示例 – 2012-03-17 16:29:16