我如何参考课程'归因于该类方法的定义?

时间:2017-09-07 19:38:55

标签: python python-3.x

我如何参考课程'是否参与了该类方法的定义?

例如:

>>> class C:
...     a = 3
...     def f(self):
...         # nonlocal a  # nonlocal doesn't work                                                                                                                                                             
...         # a = 4  # create a local variable a in f                                                                                                                                                             
...         self.a = 4
... 
>>> c=C()
>>> C.a
3
>>> c.a
4

如何在C.a的定义中引用C.f

  • 目前self.a = 4将创建与c.a不同的C.a

  • 如果self.a = 4替换为a = 4,则a将成为C.f中的本地变量,而不是C.a

    < / LI>
  • nonlocal a并未a中的f引用C.a,我想知道为什么?

感谢。

更新

在课程的定义中,何时我应该限定其属性,何时不应该?例如,我不明白为什么以下是错误的:

>>> class C:
...     C.b=4
... 
>>> C.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'b'
>>> C.C.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'C'

1 个答案:

答案 0 :(得分:1)

您需要使用该类本身:

C.a = 4

或可能

self.__class__.a = 4