mardi 25 avril 2017

How to add attributes and methods to an instance of a class

I am writing a class that needs to behave as if it were an instance of another class, but have additional methods and attributes. I've tried doing different things within __new__ but to no avail. As an example, here is a half-written class and the desired behavior:

class A(object):
    def __new__(self, a, b):
        value = 100 + a  # instances of A need to behave like integers
        ...   # bind A methods and attributes to value?
        return value

    def __init__(self, a, b)
        self.b = b

    def something(self):
        return 20 + self.b

Here is the desired behavior:

a = A(10, 5)
print(a + 10)         # 110
print(a * 2)          # 200
print(a.b)            # 5
print(a.something())  # 25

I know that when __new__ returns an instance of a class different than A, then __init__ and other methods are not bound to value. None of the other methods are either. Is this sort of thing possible? Am I thinking about this problem the wrong way?

Aucun commentaire:

Enregistrer un commentaire