在Python(2,3),我們可以將屬性功能:設置屬性之後類的創建提出了「‘instancemethod’對象有沒有屬性」,但attribiute顯然是有
>>> class A(object):
... def foo(self):
... """ This is obviously just an example """
... return "FOO{}!!".format(self.foo.bar)
... foo.bar = 123
...
>>> a = A()
>>> a.foo()
'FOO123!!'
而這涼。
但爲什麼我們不能在以後更改foo.bar
?例如,在構造函數中,像這樣:
>>> class A(object):
... def __init__(self, *args, **kwargs):
... super(A, self).__init__(*args, **kwargs)
... print(self.foo.bar)
... self.foo.bar = 456 # KABOOM!
... def foo(self):
... """ This is obviously just an example """
... return "FOO{}!!".format(self.foo.bar)
... foo.bar = 123
...
>>> a = A()
123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __init__
AttributeError: 'instancemethod' object has no attribute 'bar'
的Python聲稱沒有bar
即使它打印了罰款只是前行。
>>> A.foo.bar
123
>>> A.foo.bar = 345 # KABOOM!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'instancemethod' object has no attribute 'bar'
這裏發生了什麼,也就是爲什麼我們看到的這種行爲:如果我們試圖直接改變它的類發生
同樣的錯誤?
有沒有辦法在類創建後在函數上設置屬性?
(我知道的多方案,但我明確知道關於方法的屬性在這裏,也可能是更廣泛的問題。)
動機:Django的利用來設置屬性的可能性上的方法,如:
class MyModelAdmin(ModelAdmin):
...
def custom_admin_column(self, obj):
return obj.something()
custom_admin_column.admin_order_field ='relation__field__span'
custom_admin_column.allow_tags = True
'self.foo'不是您定義的'foo'函數。除了其他特色之外,'self.foo'取零參數,而你寫的'foo'函數需要一個參數。 – user2357112