Python self关键字:优点和缺点

时间:2014-07-04 08:45:30

标签: python-3.x

这两个类别(在性能和设计方面)之间有什么区别:

 class A:
        def methodA(self):
           self.a=10
           print(self.a)

 class B:
        def methodB(self):
           b=10
           print(b)

1 个答案:

答案 0 :(得分:0)

第二个示例中的

blocal variable,而不是class-instance (or static class) variable,因此您可以执行第一个示例:

o = A()
o.methodA()
print(o.a)

使用第二个示例导致错误,b完成后变量methodB()超出范围。

关于绩效......默认情况下,实例变量通过字典实现:

>>> class A(object):
...     def __init__(self):
...         self.a = 5
...
>>> o = A()
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__g
e__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__',
'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '_
_setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
>>> o.__dict__
{'a': 5}
>>> o.__dict__.__class__
<class 'dict'>

因此,每次访问都基本上就像执行self.__dict__['a'],效果说明here

相关问题