python - 默认为 python 类方法中的类变量?

标签 python class default-value

我正在编写一个类方法,如果没有提供其他值,我想使用类变量

def transform_point(self, x=self.x, y=self.y):

但是...这似乎不起作用:

NameError: name 'self' is not defined

我觉得有一种更聪明的方法可以做到这一点。你会怎么做?

最佳答案

您需要使用标记值,然后将其替换为所需的实例属性。 None 是一个不错的选择:

def transform_point(self, x=None, y=None):
    if x is None:
        x = self.x
    if y is None:
        y = self.y

请注意,函数签名只执行一次;您不能将表达式用于默认值,并期望这些默认值会随着每次调用函数而改变。

如果您能够将xy设置为None,那么您需要使用不同的、唯一的单例值作为默认值。在这种情况下,使用 object() 的实例通常是一个很好的哨兵:

_sentinel = object()

def transform_point(self, x=_sentinel, y=_sentinel):
    if x is _sentinel:
        x = self.x
    if y is _sentinel:
        y = self.y

现在您也可以调用 .transform_point(None, None)

关于python - 默认为 python 类方法中的类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15270693/

相关文章:

python - 使用python中的beautifulsoup从具有更多文本内容的网页中提取数据

PHP 类命名空间与前缀

JavaScript - 在类方法内动态设置类属性

php - 在 PHP 中测试可选参数

javascript - 设置 AngularJs select 的默认值,该值在 ng-options 中不存在

python - 如何discord.Invite(查看给定邀请中有多少成员)?

python - 图表中的微笑

python - django、postgres 8.4、psycopg 2.2.2、python 2.7、mod_wsgi

java - 为什么不显示此 Swing 选项卡式 Pane ?

mongodb - 如何使用自定义结构在 mongo 中进行搜索?