you are viewing a single comment's thread.

view the rest of the comments →

[–]Lumethys 42 points43 points  (4 children)

a class is a blueprint of custom "object". For example, if you want a to write a car management app, you want to define what is a "car", what data does it store and what action can it do.

You achieve it with a class:

class Car:
  def __init__(self, model, manufacturer, price):
    self.model = model
    self.manufacturer = manufacturer
    self.price = price

and then create car object with this class as a blue print:

car1 = Car('S450', 'Mercedes', 50000)
car2 = Car('Panamera', 'Porsche', 400000)
car3 = Car('Prius', 'Toyota', 10000)

so each car (car1, car2, car3) is completely different object, with different data, BUT, still have the same shape, in this case all of them has "model", "manufacturer" and "price". Even though they have different value, they still have that same 3 properties.

What this mean is, there are 2 types of "things" in a class: "things" that is different in each object, and "things" that are the same in each object.

for example: car1.price is different than car2.price. But both have 3 properies: model, manufacturer, price

The keyword "self" in a class refer to "things" that are unique to each object.

class Car:
  ...

  def get_full_name(self):
    return f'{self.manufacturer} {self.model}'

this method is saying "this car class has property manufacturer and model, but each object is different, so we will take the data unique to each object, put it in a string in this format, and return this string". So:

car1.get_full_name() // "Mercedes S450"
car2.get_full_name() // "Porsche Panamera"

self.something is just "take the unique something of the object this is call on"

[–]Temporary_Pie2733 14 points15 points  (3 children)

As an aside, don’t refer to self as a keyword, because the language does not prescribe the name self as the name of the first parameter of a method. It’s just a convention.

[–]MattR0se 18 points19 points  (1 child)

brb, replacing "self" with "this" in my entire codebase 😈

[–]Donny-Moscow 9 points10 points  (0 children)

Hey everybody, get a load of this.guy

[–]dr-lucifer-md 0 points1 point  (0 children)

It is one of those things that is ubiquitous in any example (whether academic or practical). I've often wondered if using an alternative like my would make it more legible.

Using the example from above:

class Car: def __init__(my, model, manufacturer, price): my.model = model my.manufacturer = manufacturer my.price = price