python - 如何将 cls 传递给属性而不是 self
问题描述
我知道如何在实例变量的情况下使用属性
class A():
_foo=3
@property
def foo(self):
return self.foo
a = A()
print(a.foo)
它显示_foo
3
但我不知道如何在类变量的情况下使用属性
class A():
_foo=3
@property
def foo(cls):
return cls._foo
print(A.foo)
它显示属性对象不是 3
<property object at 0x7fba8c19ea70>
如何生成类变量 getter/setter?
我在这里找到了一条路
class MetaFoo(type):
@property
def thingy(cls):
return cls._thingy
class Foo(object, metaclass=MetaFoo):
_thingy = 23
print(Foo.thingy)
它显示
23
但我想要更简单的方法。
解决方案
推荐阅读
- python - 使用位置数据进行预测
- azure-data-factory - 访问 ADF 活动运行的“详细信息”组件而不是“输出”
- excel - 将exe文件插入cron cpanel命令
- python - 在熊猫中按组合并表
- c# - 在 IGrouping 上使用 SelectMany() 时收到不明确的错误
- amazon-web-services - 在 AWS ECS 中发布微服务
- office-js - O365 Outlook 插件 - 撰写模式下的自动电子邮件解析
- spring - 如何配置 Spring Boot 以将 MultiPartFile 写入磁盘?
- json - 将嵌套数据从谷歌表发送到 API
- solr - 如何在不重新索引的情况下将唯一键更改为新字段并更新所有文档?