def add(a,b,c):
result = a + b + c
return result
x = 1
y = 2
z = 3
add = add(x,y,z)
print add(1, 2, 3)
第一个问题,上述都代码运行出错,因为函数名与变量名冲突,为什么会存在这种冲突?add()分明是一个函数,为什么会被当成变量?
class test():
def func1(self):
return 1
@property
def func2(self):
return 2
a = test()
print type(a.func1())
print type(a.func2())
第二个问题,当函数被@property修饰时,函数变为变量,因此上述代码的a.func2()报错,为什么在《flask web开发》的代码:
@auth.before_app_request
def before_request():
if current_user.is_authenticated():
current_user.ping()
if not current_user.confirmed\
and request.endpoint\
and request.endpoint[:5] != 'auth.'\
and request.endpoint != 'static':
return redirect(url_for('auth.unconfirmed'))
为什么没有报错?
is_authenticated()函数同样被@property修饰,为什么?请各位前辈讲解。
第一个问题, Python是
动态语言
,你把add
这名字重绑定
到了add(1,2,3)的结果上,也就是int
,但是int不是可调用的,所以自然报错~第二个问题, 报错是因为property装饰器将func2变为了
特性
,所以不再是一个方法。简单的例子:至于
is_authenticated
得看下原型, 看上去就是一个方法