在 Python(2 和 3)中,我们可以为函数分配属性:
>>> 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