From 579ec7341483cf8701332e4652c27158cb808dcd Mon Sep 17 00:00:00 2001 From: Kyle K Date: Wed, 2 Jun 2021 18:19:03 -0500 Subject: implement __new__ function in Square class --- foo.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/foo.py b/foo.py index 823d1f7..006df8f 100644 --- a/foo.py +++ b/foo.py @@ -1,10 +1,21 @@ class Foo: pass + def hello(): print('hello, world') + x = 13 class Square(): + def __new__(cls, x): + instance = super(Square, cls).__new__(cls) + instance.__init__(x) + return instance.squared def __init__(self, x): self.inital = x - self.squared = x**2 + self.squared = x**2 # without .self the variable would be shared among all instances + def __str__(self): + return str(self.__class__) + ": " + str(self.__dict__) + +area = Square(5.5) # if __new__ wasn't implemented, instead of 30.25 float print would call __str__ and return : {'inital': 5.5, 'squared': 30.25} +print(area) \ No newline at end of file -- cgit v1.2.3