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

1 投票
1 回答
5323 浏览
提问于 2025-04-17 22:20

我正在学习这个matplotlib的例子,但对点语法有些不理解:

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中的点似乎有不同的意思。它只是访问matplotlib的一个子模块patches,你可以查看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是初始化时定义的point变量(它不需要是固定类型)。在代码后面,有通过dr = DraggablePoint(circ)实例化的DraggablePoint对象,其中circ是一个patches.Circle对象。现在我很难理解self.point.figure。在这种情况下,figure不能是一个函数,因为后面没有()

对我来说,把它看作模块也没有意义。我猜这是一种简写,类似于self.point.get_current_figure(),它返回点绘制的图形。

同样,self.point.figure.canvas似乎就像self.point.get_current_figure().get_canvas(),它返回当前的画布。然而,在mathplotlib.patches.Circ类和mathmatplotlib.figure.Figure类中似乎没有get_current_figureget_canvas的方法(见: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?如上所述,我在文档中没有找到。

1 个回答

5

这里的 . 只是用来访问某个属性。这个属性可以是一个类、一个实例、一个方法或者函数等等。当你看到像 a.b.c 这样的写法时,它指的是 a 的属性 b 中的属性 c,而 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)

撰写回答