名前が同じ場合、Pythonはクラス属性、インスタンス属性、およびメソッドをどのように区別しますか?
class Exam(object):
test = "class var"
def __init__(self, n):
self.test = n
def test(self):
print "method : ",self.test
test_o = Exam("Fine")
print dir(test_o)
print Exam.test
print test_o.test
test_o.test()
出力:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'test']
<unbound method load.test>
Fine
Traceback (most recent call last):
File "example.py", line 32, in <module>
test_o.test()
TypeError: 'str' object is not callable
呼び方
- クラス属性、
Exam.test
--><unbound method load.test>
出力はメソッドを示します - インスタンス属性
test_o.test
-->"Fine"
- メソッド
test_o.test()
-->TypeError: 'str' object is not callable