Mar-26-2020, 02:19 PM
Hi, everyone. I'm happy to have found this forum. I believe this is a basic question about __init__, but I haven't been able to find an answer online. I'll appreciate any help and insight you can offer.
Q: Online I have seen the def __init__(self) statement for a class written with parameters that are initialized in the same line, and others that don't include parameters and initialize them in the body of the block. For example, please compare these two short snippets of code:
What's the difference?
Why in the first version do we use self.x = 0, but in the second version we initialize x and y in the __init__ line and then we use self.x = x?
Is there a reason, convention, advantage to using one method over another?
And what does it actually mean to say, self.x = x?
Thanks very much for your help!
David
Q: Online I have seen the def __init__(self) statement for a class written with parameters that are initialized in the same line, and others that don't include parameters and initialize them in the body of the block. For example, please compare these two short snippets of code:
class Robot(): def __init__(self): self.x = 0 self.y = 0 def move_robot(self, x_increment=1, y_increment=1): self.x += x_increment self.y += y_increment robot01 = Robot() robot01.move_robot(3,5) print('Bot x,y =', robot01.x, robot01.y)and this one:
class Robot(): def __init__(self, x=0, y=0): self.x = x self.y = y def move_robot(self, x_increment=1, y_increment=1): self.x += x_increment self.y += y_increment robot01 = Robot() robot01.move_robot(3,5) print('Bot x,y =', robot01.x, robot01.y)They both produce the same output.
What's the difference?
Why in the first version do we use self.x = 0, but in the second version we initialize x and y in the __init__ line and then we use self.x = x?
Is there a reason, convention, advantage to using one method over another?
And what does it actually mean to say, self.x = x?
Thanks very much for your help!
David