Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
20.4. Adding Parameters to the Constructor¶
Our constructor so far can only create points at location
(0,0). To create a point at position (7, 6) requires that we
provide some additional capability for the user to pass information to the constructor. Since constructors are simply specially named functions, we can use parameters (as we’ve seen before) to provide the specific information.
We can make our class constructor more generally usable by putting extra parameters into
__init__ method, as shown in this example.
class Point: """ Point class for representing and manipulating x,y coordinates. """ def __init__(self, initX, initY): self.x = initX self.y = initY p = Point(7,6)
Now when we create new points, we supply the x and y coordinates as parameters. When the point is created, the values of
initY are assigned to the state of the object, in the instance variables x and y.
This is a common thing to do in the
__init__ method for a class: take in some parameters and save them as instance variables. Why is this useful? Keep in mind that the parameter variables will go away when the method is finished executing. The instance variables, however, will still be accessible anywhere that you have a handle on the object instance. This is a way of saving those initial values that are provided when the class constructor is invoked.
Later on, you will see classes where the
__init__method does more than just save parameters as instance variables. For example, it might parse the contents of those variables and do some computation on them, storing the results in instance variables. It might even make an Internet connection, download some content, and store that in instance variables.
Check Your Understanding
Create a class called
NumberSetthat accepts 2 integers as input, and defines two instance variables:
num2, which hold each of the input integers. Then, create an instance of
NumberSetwhere its num1 is 6 and its num2 is 10. Save this instance to a variable