This isn’t for anything I’m working on yet, it’s just some test code as I’m just learning class methods and suck. But say I have the following code
class Test(int):
def __init__(self,arg):
self = arg
def thing(self):
self += 10
and going,
foo=Test(12) sets foo to 12. However I want it, so when I do, foo.thing(), foo increases by 10. So far, going foo.thing() just keeps it at 12. How would I change this code to do that.
Because
intis a immutable, you cannot magically turn it into a mutable type.Your methods are no-ops. They change
selfin the local namespace, by reassigning it to something else. They no longer point to the instance. In other words, both methods leave the original instance unaltered.You cannot do what you want to do with a subclass of
int. You’ll have to create a custom class from scratch using the numeric type hooks instead.Background:
inthas a__new__method that assigns the actual value toself, and there is no__iadd__method to support in-place adding. The__init__method is not ignored, but you can leave it out altogether since__new__already did the work.Assigning to
selfmeans you just replaced the reference to the instance with something else, you didn’t alter anything aboutself:Because
intdoes not have a__iadd__in-place add method, yourself += 2is interpreted asself = self + 2instead; again, you are assigning toselfand replacing it with a new value altogether.