Can a class be thought of as a library and the method as the portion of the module you wish to import?
Is it best practice to save the class in a variable like class = Class() before calling methods or is it a matter of preference as the two scripts below yield the same answer.
Hi, I have a question regarding variables in a class.
In this exercise there was the following code:
class Circle():
pi=3.14
def area(self, radius):
return Circle().pi*radius**2
Why can’t you call pi straight away. It’s a variable that has already been defined within the scope of the class. At least, that is what I assumed. Why do you need to call the variable with self or ClassName?
A lot of these exercises are just to get you used to working with classes in general. Whilst you could “solve” a particular requirement without them and kudos for doing so it’s best to try and follow the guidance even if it takes longer to understand/type out because it’s just an introduction to the topic but it is most definitely worth learning.
Ok let’s step back for a second. A class is a template for creating objects. Think of it like a blueprint for making houses. We would then say each house is an object, or instance of the class.
So the word self just refers to a specific house, i.e a specific object in our scenario. Try reading it as “this specific house itSELF”. The word self is a convention in Python, though it can technically be any word you want. To illustrate with code:
class Blueprint:
def __init__(self, name):
self.name = name
house_one = Blueprint('first house')
house_two = Blueprint('second house')
So here we have our class, BluePrint. We have also created two objects from it. So when we’re creating house_one, the parameter self refers to house_one itSELF. So it’s saying "hey, let’s give the object or instance being created a name to itSELF. That name being the argument passed into the parantheses (‘first house’ in this case). Then when we make the second object, self refers to house_two and follows the same process.
Note: The reason why the __init__ method has two parameters whereas we only pass one argument when we create the object is because self is actually passed in but implicitly. So basically you might think ‘first house’ was the first argument passed in the parantheses but it was actually self under the hood. Python just does that for us automatically
Hope that makes sense. Feel free to ask if anything is unclear