Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
__init__ question
#1
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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
Reply


Messages In This Thread
__init__ question - by dcollett - Mar-26-2020, 02:19 PM
RE: __init__ question - by buran - Mar-26-2020, 02:30 PM
RE: __init__ question - by dcollett - Mar-26-2020, 04:02 PM
RE: __init__ question - by buran - Mar-26-2020, 04:11 PM
RE: __init__ question - by Marbelous - Mar-26-2020, 04:32 PM
RE: __init__ question - by dcollett - Mar-26-2020, 06:19 PM
RE: __init__ question - by dcollett - Mar-26-2020, 07:45 PM
RE: __init__ question - by buran - Mar-26-2020, 07:59 PM
RE: __init__ question - by dcollett - Mar-26-2020, 08:06 PM
RE: __init__ question - by buran - Mar-26-2020, 08:08 PM
RE: __init__ question - by dcollett - Mar-26-2020, 08:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Initiating an attribute in a class __init__: question billykid999 8 3,035 May-02-2023, 09:09 PM
Last Post: billykid999
  Why is there an __init__ statement within the __init__ definition iFunKtion 7 7,491 Feb-06-2017, 07:31 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020