python - Python 中的点语法是什么意思?

标签 python syntax

我正在学习this matplotlib example ,但不理解点语法:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
class DraggablePoint:
    lock = None #only one can be animated at a time
    def __init__(self, point):
        self.point = point
        self.press = None
        self.background = None

    def connect(self):
        'connect to all the events we need'
        self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.cidrelease = self.point.figure.canvas.mpl_connect('button_release_event', self.on_release)
        self.cidmotion = self.point.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        if event.inaxes != self.point.axes: return
        if DraggablePoint.lock is not None: return
        contains, attrd = self.point.contains(event)
        if not contains: return
        self.press = (self.point.center), event.xdata, event.ydata
        DraggablePoint.lock = self

        # draw everything but the selected rectangle and store the pixel buffer
        canvas = self.point.figure.canvas
        axes = self.point.axes
        self.point.set_animated(True)
        canvas.draw()
        self.background = canvas.copy_from_bbox(self.point.axes.bbox)

        # now redraw just the rectangle
        axes.draw_artist(self.point)

        # and blit just the redrawn area
        canvas.blit(axes.bbox)

    def on_motion(self, event):
        if DraggablePoint.lock is not self:
            return
        if event.inaxes != self.point.axes: return
        self.point.center, xpress, ypress = self.press
        dx = event.xdata - xpress
        dy = event.ydata - ypress
        self.point.center = (self.point.center[0]+dx, self.point.center[1]+dy)

        canvas = self.point.figure.canvas
        axes = self.point.axes
        # restore the background region
        canvas.restore_region(self.background)

        # redraw just the current rectangle
        axes.draw_artist(self.point)

        # blit just the redrawn area
        canvas.blit(axes.bbox)

    def on_release(self, event):
        'on release we reset the press data'
        if DraggablePoint.lock is not self:
            return

        self.press = None
        DraggablePoint.lock = None

        # turn off the rect animation property and reset the background
        self.point.set_animated(False)
        self.background = None

        # redraw the full figure
        self.point.figure.canvas.draw()

    def disconnect(self):
        'disconnect all the stored connection ids'
        self.point.figure.canvas.mpl_disconnect(self.cidpress)
        self.point.figure.canvas.mpl_disconnect(self.cidrelease)
        self.point.figure.canvas.mpl_disconnect(self.cidmotion)

fig = plt.figure()
ax = fig.add_subplot(111)
drs = []
circles = [patches.Circle((0.32, 0.3), 0.03, fc='r', alpha=0.5),
               patches.Circle((0.3,0.3), 0.03, fc='g', alpha=0.5)]

for circ in circles:
    ax.add_patch(circ)
    dr = DraggablePoint(circ)
    dr.connect()
    drs.append(dr)

plt.show()

现在以该行为例

ax.add_patch(circ)

这对我来说似乎很清楚。 axes 类有一个名为 add_patch 的方法,该方法将(特别是)Circle 对象作为参数。因此,ax.add_patch(circ) 只需从对象 ax 调用此方法,该对象是 axes 实例。

import matplotlib.patches 中的点似乎有不同的含义。它只是访问模块 patches,它是 matplotlib 的子模块,请参阅 http://matplotlib.org/1.3.1/py-modindex.html获取模块列表。

据我所知,模块只是一个包含一些类和函数的 Python 文件。

现在考虑:

self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press)

self.point 是 init 中定义的 point 变量(不需要是固定类型)。后面的代码中有通过 dr = DraggablePoint(circ) 实例化的 DraggablePoint 对象,其中 circpatches.Circle > 对象。现在我很难解释self.point.figure。本例中的 figure 不能是函数,因为末尾没有 ()

对我来说,在这种情况下将其视为模块也是没有意义的。我猜它是类似 self.point.get_current_figure() 的简写类型,它返回绘制点的图形。

类似地,self.point.figure.canvas似乎类似于self.point.get_current_figure().get_canvas(),它返回当前 Canvas 。然而,在 mathplotlib.patches.Circ 类中似乎没有 get_current_figureget_canvas 方法。 mathmatplotlib.figure.Figure 类(请参阅: http://matplotlib.org/1.3.1/api/artist_api.html#module-matplotlib.patcheshttp://matplotlib.org/1.3.1/api/figure_api.html#matplotlib.figure.Figure )。

如果有人能为我澄清这一点,那就太好了。更一般地说:

  • Python 中的点表示法似乎有多种不同的含义。有哪些,它们是如何称呼的以及我如何知道使用哪一个?

  • 如何才能看到我可以从 matplotlib API 文档调用 self.point.figureself.point.figure.canvas?如上所述,我在文档中没有找到它。

最佳答案

. 只是访问一个属性。属性可以是类、实例、方法/函数等。当您看到类似 a.b.c 的内容时,它指的是属性 的属性 c b of a,其中 abc 可以是上述任何类型多于。换句话说,它是a.b的属性c

最后没有 () 的事实意味着该属性不是函数。考虑以下因素:

>>> class Foo:
...     def __init__(self):
...         import os
...         self.number = 1
...         self.module = os
...         self.class_ = Exception
...         self.function = dir
... 
>>> f = Foo()

模块可以是属性:

>>> f.module
<module 'os' from '/usr/lib/python2.7/os.pyc'>
>>> f.module.path.join('foo', 'bar')
'foo/bar'

类可以是属性:

>>> f.class_
<type 'exceptions.Exception'>
>>> raise f.class_('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: foo

函数可以是属性:

>>> f.function
<built-in function dir>
>>> f.function('.')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

如果您想知道是否可以调用某些内容,请使用callable函数:

>>> callable(f.module)
False
>>> callable(f.function)
True

如果您想了解属性是什么或如何使用它,请首先使用 help 函数读取其文档字符串。例如:

help(f.function)

关于python - Python 中的点语法是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22410826/

相关文章:

c++ - 有没有办法在 c++ 中禁用旧的 c 样式转换

python - IP 转发,scapy 中的 MiTM

python - Django:CSS 和图像(静态文件)加载成功但未应用

python - 将应用程序级别设置注入(inject) Django 中的项目级别设置

c++ - "int &temperature"与 C++ 中的 "int& temperature"相同吗?

javascript - 没有 TypeError 的深度 Javascript 检查是否未定义

python - 直方图和直方图边界框

python - 迭代时字符串被视为字符组

Cobol 的语法帮助

haskell - 是否可以使用记录语法声明约束数据类型?