python - 如何使用关键字作为变量名?

标签 python keyword

我有以下带有变量 fromtorate 的类。 来自keyword .如果我想在下面的init方法中使用它,正确的写法是什么?

更多上下文:该类显式需要 from 变量,因为它是另一个开发人员用不同语言编写的 POST 端点所需的 json 的一部分。所以改变变量名是不可能的。

class ExchangeRates(JsonAware):
    def __init__(self, from, to, rate):
        self.from = from
        self.to = to
        self.rate = rate

JsonAware 代码:

class PropertyEquality(object):
    def __eq__(self, other):
        return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%s' % (k, v) for (k, v) in self.__dict__.items()]))

class JsonAware(PropertyEquality):
    def json(self):
        return json.dumps(self, cls=GenericEncoder)

    @classmethod
    def from_json(cls, json):
        return cls(**json)

通用编码器代码:

class GenericEncoder(json.JSONEncoder):
    def default(self, obj):
        return obj.__dict__

最佳答案

在您的首选名称中添加一个下划线:来自 _ 和 _

(参见 PEP 8)

class ExchangeRates(JsonAware):
    def __init__(self, from_, to_, rate):
        self.from = from_
        self.to = to_
        self.rate = rate

关于python - 如何使用关键字作为变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968516/

相关文章:

python - 在 Vagrant 配置期间更新 .bashrc 和环境变量

Python Makefile 库

mysql - SQL MACH() AGAINST() 关键字长度

groovy - 关于省略 'return' 关键字以返回 Groovy 中的闭包 block 的不一致

.net - 你能创建你自己的默认 T 其中 T 是你自己的类

python - 如果元组具有相同的第一个元素,如何聚合元组列表的元素?

python - 如何在word文件(.docx)python中将两张图片放在同一级别

python - 使用 Tweepy 抓取抓取坐标并绘制它们

d - 什么是纯变量?

php - 如何在字符串中搜索数千个可能的关键字