【问题标题】:What types of attributes does the dir function give in python?dir函数在python中给出了哪些类型的属性?
【发布时间】:2015-10-15 00:34:52
【问题描述】:

我在某处读到 python 中的一切都是对象。我想,2号呢?如果我在 python 解释器中输入“dir(2)”,我会得到以下输出:

目录(2) ['__abs__','__add__','__and__','__class__','__cmp__','__coerce__','__delattr__','__div__','__divmod__','__doc__','__float__','__floordiv__',' __format__','__getattribute__','__getnewargs__','__hash__','__hex__','__index__','__init__','__int__','__invert__','__long__','__lshift__','__mod__','__mul__' ,'__neg__','__new__','__nonzero__','__oct__','__or__','__pos__','__pow__','__radd__','__rand__','__rdiv__','__rdivmod__','__reduce__',' __reduce_ex__','__repr__','__rfloordiv__','__rlshift__','__rmod__','__rmul__','__ror__','__rpow__','__rrshift__','__rshift__','__rsub__','__rtruediv__','__rxor__' ,'__setattr__','__sizeof__','__str__','__sub__','__subclasshook__','__truediv__','__trunc__','__xor__','bit_length','共轭','分母','imag','分子', '实数']

显然,数字 2 是具有这些属性的对象。我得到了数字 2 的几个属性名称,例如 __add__ 和共轭。但是如果我尝试 2.conjugate(),我会得到一个错误

2.conjugate() SyntaxError: 无效语法

但是 dir(2j) 将 conjugate 作为方法,当我使用方法 conjugate 时我没有收到错误。

2j.conjugate() -2j

2.0.conjugate() 2.0

也没有给我带来任何问题。

更奇怪的是,2.__add__() 和 2.__add__ 给出了错误,即使它是 2 的属性。我认为 add 指的是 + 操作。那么为什么它在属性列表中显示为 __add__ 而不是 + 呢? dir(2) 是 2 的变量和方法列表还是列出了其他内容? __thing__ 和 thing 有什么区别?什么时候可以以常规方式调用方法,比如 object.method(),什么时候需要做一些时髦的事情,比如 2+2 而不是 2.add(2)?

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    conjugateint的方法,可以应用于int对象。

    为了演示,所有这些工作:

    x = 2; x.conjugate()
    (2).conjugate()
    2 .conjugate()  # note the whitespace
    

    由于 python 解析器对数字文字有特殊处理,它不允许这种尴尬的语法:

     2.conjugate()
    

    正如@ignacio 所解释的,这是因为解析器看到2. 并将其视为浮点数,即类似于(2.)conjugate(),这不是有效的语法。

    但是,除了将其与此语法一起使用之外,还允许执行该操作,如上所示。

    对于__add____add__ 方法允许类型定义/覆盖+ 操作符如何应用于它们。当您执行a+b 时,解释器会调用a.__add__(b)b.__add__(a)(机制比这更复杂)。

    通常,您不必直接致电__add__

    【讨论】:

      【解决方案2】:

      解析器看到“.”并认为浮动是预期的。

      >>> (2).conjugate
      <built-in method conjugate of int object at 0x2242140>
      

      剩下的:

      Python Language Reference, Data Model section

      【讨论】:

      • 从技术上讲,是词法分析器而不是解析器对源“令牌”的构成做出较低级别的决定。由于2. 是一个有效的令牌,解析器永远无法看到句点。
      猜你喜欢
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      相关资源
      最近更新 更多