I want to create a class attribute, that are dependent to another class attribute (and I tell class attribute, not instance attribute). When this class attribute is a string, as in this topic, the proposed solution
class A:
foo = "foo"
bar = foo[::-1]
print(A.bar)
works fine. But when the class attribute is a list or a tuple, as in my case, the following code dose not work...
x=tuple('nice cup of tea')
class A:
remove = ('c','o','a',' ')
remains = tuple(c for c in x if not c in remove)
print(A.remains)
raise
Traceback (most recent call last):
File "[***.py]", line 3, in <module>
class A:
File "[***.py]", line 5, in A
remains = tuple(c for c in x if not c in remove)
File "[***.py]", line 5, in <genexpr>
remains = tuple(c for c in x if not c in remove)
NameError: name 'remove' is not defined
Why this kind of methods works if my class attributes is less complex (as simple string, as in the mentioned previous topic) but not for tuple?
After investigations, I found this way:
x=tuple('nice cup of tea')
def sub(a,b):
return tuple(c for c in a if not c in b)
class A:
remove = ('c','o','a',' ')
remains = sub(x, remove)
print(A.remains)
that works, but does not suit me, for these reasons:
- I don't understand why this one, via an intermediary function, works and not without.
- I don't want to add a function for just a single line with an elementary operation.