Reputation: 2359
Python has the usual bitwise operators, like ~
, &
, |
, etc. and in-place operators like +=
, &=
, etc. to simplify expressions like:
a = a & 34234
a = a + 577
To:
a &= 34234
a += 577
Despite the complement operator ~
being an unary function, and not following the same structure because it isn't used with two values (like a
and 34234
), can expressions like these be simplified with another type of operator?
a = ~a # not bad at all
# Still easy to code but seems redundant
self.container.longVariableName.longName = ~self.container.longVariableName.longName
Upvotes: 2
Views: 692
Reputation: 11849
If you are only concerned about doing this for attributes of object instances, you could write a method like:
def c(obj, atr):
setattr(obj,atr,~getattr(obj,atr))
and then use it like:
c(self.container.longVariableName, 'longName')
I think that @TimPeters answer is much better, but thought I'd provide this in case it is useful to anyone in the future who needs to do this with non-integers are is happy to only work with instant attributes
Upvotes: 2
Reputation: 70592
It's excruciatingly obscure, but:
self.container.longVariableName.longName ^= -1
does the job, so long as the values you're dealing with are integers. "Are integers" is required so that there's an exploitable mathematical relation between the ~
and ^
operators.
Why it works:
Upvotes: 3