【问题标题】:How to do python class like pygame.Rect? [duplicate]如何做像pygame.Rect这样的python类? [复制]
【发布时间】:2021-08-05 22:02:21
【问题描述】:

我想知道,如何做像 pygame.Rect 这样的 python 类。我的意思是如何创建一个类,当您更改一个变量时,其他变量也会更改(使用 pygame Rect 您可以更改例如变量 x 和自动变量 centerx 更改以适应)

【问题讨论】:

  • this 会回答您的问题吗?您还可以在使用之前更改函数中的变量。例如像centerx这样的变量,它总是与x成比例,因此您可以在函数中使用centerx之前将centerx设置为基于x的值。

标签: python pygame


【解决方案1】:

您说的是属性设置器和获取器!这是一个带圆圈的玩具示例:

import math

class Circle:
    def __init__(self, radius):
        self._radius = radius
        self.update_from_radius()

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, val):
        self._radius = val
        self.update_from_radius()

    def update_from_radius(self):
        self.area = self._radius*self._radius*math.pi
        self.circumference = 2*self._radius*math.pi
        self.diameter = 2*self._radius

c = Circle(4)
print(c.area) >>> 50.26548245743669

c.radius = 8
print(c.area) >>> 201.06192982974676

如果您想了解更多信息,请查看here,它给出了很好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2013-02-19
    • 2016-03-22
    • 2016-11-22
    相关资源
    最近更新 更多