我如何从方法列表中判断出哪些已在该类中定义,哪些方法已被继承?

时间:2011-01-15 08:15:52

标签: python inheritance

我如何从方法列表中判断出哪些已在该类中定义,哪些已被继承?例如。我有一个银行模块,有两个类,BankAccount和Transactions。 Transcations继承自BankAccount

>>> dir(bank.BankAccount) 
[ 'chk', 'interest']
>>> dir(bank.Transcations) 
[ 'chk', 'deposit', 'interest', 'withdraw']

我如何检查'chk'和'interest'方法是否被继承,是否可以判断从哪个类继承而来?

2 个答案:

答案 0 :(得分:3)

>>> class BankAccount(object):
...     def deposit(self):
...             pass
...     def account_no(self):
...             pass
... 
>>> class Transaction(BankAccount):
...     def withdrawal(self):
...             pass
... 
>>> Transaction.__dict__.keys()
['__module__', '__doc__', 'withdrawal']
>>> BankAccount.__dict__.keys()
['__module__', 'deposit', '__dict__', '__weakref__', '__doc__', 'account_no']

答案 1 :(得分:2)

您可以查看bank.Transactions.__dict__.keys()