【问题标题】:Python attrs with Random Attribute Value?具有随机属性值的 Python attrs?
【发布时间】:2021-06-07 17:12:22
【问题描述】:

我使用attrs 来创建类A,其属性为surprise,然后每次访问它时都应该返回一个不同的随机值(可能从可能的值列表中选择)。

@attr.s
class A(object):
   surprise = attr.ib(type=str)

我们如何为类的surprise 属性的访问添加一个钩子?这个钩子可以让我们在每次访问surprise属性时生成一个新的字符串值。

谢谢!

期望:

a = A()
print a.surprise   # foo
print a.surprise   # bar
print a.surprise   # another_random_str

【问题讨论】:

  • 你不能每次都使用@property装饰器为surprise返回一个新值吗?

标签: python python-2.x python-attrs


【解决方案1】:

应该这样做:

from random import randint
class A:
    my_vars = ["str1", "str2", 1, 2, "whatever"]
    @property
    def surprise(self):
        return self.my_vars[randint(0, len(self.my_vars)-1)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2019-09-19
    • 1970-01-01
    相关资源
    最近更新 更多