转载自:http://blog.iamzsx.me/show.html?id=183004
熟悉Java的人在学习Python的时候可能会由于写Java代码的习惯,会为class内部的成员变量写一下get和set函数,然后外部通过get和set函数访问,而不是直接访问成员变量。例如,可能会写出下面类似的代码:
01 | class Test( object ): |
02 |
03 | def __init__( self ): |
04 | self .__foo = 0 |
05 | |
06 | def get_foo( self ): |
07 | return self .__foo |
08 | |
09 | def set_foo( self , foo): |
10 | self .__foo = foo |
然而,跟Java有所不同(
Java中使用get或set函数访问成员变量会影响性能吗?),在Python中通过get和set函数访问与直接访问成员变量的性能差距是很大的。
下面我们来做一个简单的实验(测试版本:Python 2.7)。
代码一:使用get和set函数来访问成员变量。
01 | import time |
02 |
03 | class Test( object ): |
04 |
05 | def __init__( self ): |
06 | self .__foo = 0 |
07 | |
08 | def get_foo( self ): |
09 | return self .__foo |
10 | |
11 | def set_foo( self , foo): |
12 | self .__foo = foo |
13 |
14 | test = Test() |
15 | begin = time.time() |
16 | for i in xrange ( 0 , 10000000 ): |
17 | test.set_foo(test.get_foo() + i * i) |
18 | print time.time() - begin |
运行时间5.8秒左右。
代码二:直接访问成员变量
01 | import time |
02 |
03 | class Test( object ): |
04 |
05 | def __init__( self ): |
06 | self .foo = 0 |
07 |
08 | test = Test() |
09 | begin = time.time() |
10 | for i in xrange ( 0 , 10000000 ): |
11 | test.foo = test.foo + i * i |
12 | print time.time() - begin |
运行时间3.4秒左右。
可以看出直接访问成员变量的性能远高于通过get和set函数访问。
因此,如果没有使用get和set函数的必要,就不要使用了。
另外,也要尽量减少Property的使用,这个比通过get和set函数访问的性能还低。
下面的使用Property写的代码的运行时间是6.7秒左右。
01 | import time |
02 |
03 | class Test(object): |
04 |
05 | def __init__(self): |
06 | self.__foo = 0 |
07 | |
08 | def _get_foo(self): |
09 | return self.__foo |
10 | |
11 | def _set_foo(self, foo): |
12 | self.__foo = foo |
13 | |
14 | foo = property(_get_foo,_set_foo) |
15 |
16 | test = Test() |
17 | begin = time.time() |
18 | for i in xrange( 0 , 10000000 ): |
19 | test.foo = test.foo + i * i |
20 | print time.time() - begin |