Làm thế nào để python phân biệt một thuộc tính lớp, thuộc tính instance và phương thức khi các tên giống nhau?python: Điều gì xảy ra khi thuộc tính lớp, thuộc tính instance và phương thức tất cả đều có cùng tên?
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()
Output:
['__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
Làm thế nào để gọi
- thuộc tính lớp,
Exam.test
-><unbound method load.test>
đầu ra cho thấy phương pháp - dụ thuộc tính
test_o.test
->"Fine"
- phương pháp
test_o.test()
->TypeError: 'str' object is not callable
gì sai với gọi test_o.test()? – naren
@naren bạn đang cố gắng gọi cho thành viên cá thể; xem ở trên. – ecatmur