+ 3

How is this possible?

I'm wondering right now. Look at this example: class BendedTube: def __init__(self, points=False): self.p = points if points: self.calc() def length_of_line(self, p1, p2): L = 0 for i in range(3): L += (p1[i]-p2[i])**2 return L**0.5 def calc(self): #theoretical lengths from point to point self.theoretic_len = list((map(self.length_of_line, self.p, self.p[1:]))) Here, I'm using an Object-Method [self.calc()] in the Constructor. And this works!? I think, nobody told me, that this is possible. No idea how this work, to use an Object-Method from an Object that does not exist. Is this Python specific? Or can one do so in other languages?

3rd Nov 2019, 11:58 AM
Coding Cat
Coding Cat - avatar
7 Antworten
+ 5
Before calling __init__ magic function, another method is called : __new__. His goal is to really create the object. class A() : def __new__(cls) : return object.__new__(cls) def __init__(self) : #all you want __init__'s purpose isn't to create the object but to initialize it. Here is the whole process. - create a new type, A, with all methods - instantiate the class A by calling function __new__ - initialize the object by calling the method __init__
3rd Nov 2019, 2:07 PM
Théophile
Théophile - avatar
+ 3
Everything in python is an object. Classes are objects as well. So you can instantiate a class without any other object.
3rd Nov 2019, 12:40 PM
Qasem
+ 2
Thx Théophile "__init__'s purpose is...." That's the point. Now I god it 😀
3rd Nov 2019, 2:35 PM
Coding Cat
Coding Cat - avatar
+ 2
Thanks to you both. For me, it was not clear, that the object already exist when __int__ is called.
3rd Nov 2019, 6:18 PM
Coding Cat
Coding Cat - avatar
+ 1
I agree with second part and that's my first answer.
3rd Nov 2019, 4:25 PM
Qasem
0
Théophile I think the question is that when we have no object i.e. """" class Myclass: ... Myclass() """" What's the object in "object._new__(cls)"? Obviously when we instantiate class with: obj = Myclass() Everything is clear. But what about in our case?
3rd Nov 2019, 3:40 PM
Qasem
0
In the case he is talking about (in the constructor), the object is already created, so it is allowed to call an object method. This object is represented by self, so we have an object, right? Concerning the object in 'object.__new__', it is because all objects are derived from base class object. When we do : obj = Myclass(), we in fact do : obj = Myclass.__new__(Myclass) obj.__init__()
3rd Nov 2019, 4:04 PM
Théophile
Théophile - avatar