python 继承 class 函数

python inheritance class functions

pillow 库的 ImageDraw 模块中,有一个名为 _compute_regular_polygon_vertices 的辅助函数(第 774 行)。

使用此代码,我尝试将其与继承的 class 一起使用,但它无法使用继承的 class 名称:

from PIL import Image, ImageDraw


class Test(ImageDraw.ImageDraw):
    def my_first_method(self):
        # this works
        ImageDraw._compute_regular_polygon_vertices((50, 50, 50), 3, 0)

    def my_second_method(self):
        # this fails
        Test._compute_regular_polygon_vertices((50, 50, 50), 3, 0)


img = Image.new("L", (100, 100))
ctx = Test(img)

ctx.my_first_method()
ctx.my_second_method()

这是否意味着 class 函数仅限于初始 class?

编辑: @thomas 令我困惑的是 class 函数实际上是继承的:

class A:
    def __init__(self):
        pass
    
    def _private_get():
        return 0
    
class B(A):
    def get_a():
        return B._private_get()

b = B()
B.get_a()

此外,ImageDraw.py 的第 249 行我们可以看到 _compute_regular_polygon_vertices 没有任何 class 前缀...这怎么可能?

您对模块 ImageDraw 和 class ImageDraw 感到困惑。 class ImageDraw 在模块 ImageDraw 中实现。方法 _compute_regular_polygon_vertices 在模块内部,但不是 class 的方法。 所以它不能与你的 class.

一起继承