get_summary.
Methods are functions that are “owned by” the class.
About methods
Methods are owned by the class and must be part of the class definition. The definition must be indented to the same degree as the properties, like in the example above. Class methods typically have to include at least one parameter, the keyword ‘self’. This is a placeholder parameter, and when the code is actually run Python goes behind the scenes and supplies the argument that self accepts: the instance of the class it is being called from. This allows you to access the class instance’s properties and methods from within the method. For example
Not all methods need to use the self parameter because sometimes methods don’t need to know about the instance’s methods and properties. These are a special type of method known as static methods, and there’s a special way of handling them that we’ll cover in a later article.
- Repeated notes on
selffrom Part 1.- Calling
self“self” is actually a convention thing and you could technically use any name you like (so long as it’s consistent within your class). - However, everyone uses
selfso you may just introduce a lot of unnecessary confusion if you decided to. - If you’ve ever called a method on an object in the past with an argument when you shouldn’t have you may have seen
TypeError: HatchBack.get_summary() takes 1 positional argument but 2 were given, or a variant, before. This is why!selfcounts as a parameter and the argument is automatically supplied by Python at runtime, so if you try to add something in it complains of getting two arguments because Python already gave the method one when we weren’t looking.
- Calling
Creating a method
Let’s wrap up by putting all the above to use. Let’s suppose we are asked by a customer to be able to get the mass of the car in the data class in lbs instead of kg. We draw up a spec.- The mass must be accessible the same way but with different units
- The units must be specified by the user
- The units can only be SI or Imperial
- SI should be the default
imperial: bool = False. Then if the user adds True as a parameter we know they want imperial units, otherwise they’ll get their answer in SI units.
Here’s what it looks like so far.
imperial is False we just need to return the mass as is but if it’s True we need to convert to lbs, by multiplying the mass by 2.205. We can access the mass to return it by calling the representation of that instance self. This is pretty straightforward and the code below shows how I would do it.
return statements in the method, don’t worry! Python will always execute the one it gets to first and ignore the other one. If you’re still confused I recommend checking out this great RealPython article on the matter: The Python return Statement.