Issue
I am using attrs
to create the class A
with attribute surprise
then should return a different random value (maybe choosen from a list of possible values) everytime it is accessed.
@attr.s
class A(object):
surprise = attr.ib(type=str)
How can we add a hook to the accessing of the surprise
attribute of the class? This hook can allow us to generate a new string value on each access of the surprise
attribute.
Thanks!
Desired:
a = A()
print a.surprise # foo
print a.surprise # bar
print a.surprise # another_random_str
Solution
This should do it:
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)]
Answered By - trozzel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.