#๐Ÿ”’ Classes

89 messages ยท Page 1 of 1 (latest)

thick wyvernBOT
#

@proper depot

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

hardy rose
#

That's imagine you need to represent a Car

proper depot
hardy rose
#

What in the car you can observe(attribute/properties), and what the car can do

proper depot
#

so for example

#

class Car:
def init (self, brand: str, type: str)

#

like this?

hardy rose
#

You only have taken the input, but never stored them

proper depot
hardy rose
#

No, __init__ is just define how you receive the input

proper depot
#

How does it work then?

hardy rose
#

Like Car("Brand", "Type data whatever")

#

You have the self, which is the instance of the class

#

You store them in the instance

proper depot
#

then why did this guy do it like this?

https://www.youtube.com/watch?v=JH4q65dZPvY

What exactly is 'self' in Python? Well that's what we're going to go over today in detail. Once you understand, working with classes will be a piece of cake!

Static methods: https://youtu.be/JQZmzrCSKSY

โ–ถ Become job-ready with Python:
https://www.indently.io

โ–ถ Follow me on Instagram:
https://www.instagram.com/indentlyreels

โ–ถ Play video
hardy rose
#

That what I described
Look at line 3/4 in the thumbnail

#

It is the process of storing the attribute to the instance of the class

fair raptor
#

Can you share the code in question. As text

hardy rose
fair raptor
#

Just share it as text please instead of relying on a join that you need to approve

hardy rose
#

It is just for explaining where he could edit the same thing at the same time

fair raptor
proper depot
#

let me and the other guy talk

proper depot
#

since the way you just wrote it has no instance

hardy rose
#

Oh, that one is just to get the instance

proper depot
#

trying to understand how classes originally work

hardy rose
#
class Car:
    def __init__(self, brand, type): # Define what to be input when creating an instance(initialising)
    # self is automatically put by python and you do not put that when calling
        self.brand = brand # Storing to instance
        self.type = type

Car("Brand", "Type whatever") # Which would call the initialise function
fluid isle
#

There's a bit of magic happening when you call Car("Volvo", "diesel") to construct a new instance. It already has called a different internal method, __new__, which creates the actual new object. It then calls __init__, passing the new instance as the argument self, and your other arguments into brand and type.

From "outside" the class, you don't use self directly. It's used automatically when you call some instance method.

#

!e

class Car:
    def __init__(self, brand, fuel_type):
        self.brand = brand
        self.fuel_type = fuel_type

    def describe(self):
        print(f"I'm a {self.brand} with fuel type {self.fuel_type}")

mycar = Car("Volvo", "diesel")
mycar.describe()
thick wyvernBOT
fluid isle
#

Notice how .describe() is called with no argument.
Because it's being called from the mycar instance, it automatically passes that same instance in place of the self argument.

hardy rose
#
class Car:
    def __init__(self, brand, type): # Define what to be input when creating an instance(initialising)
    # self is automatically put by python and you do not put that when calling
        self.brand = brand # Storing to instance
        self.type = type
    
    def check_equal(self, other_car):
        # self is automatically added by python
        return self == other_car

c1 = Car("Brand", "Type whatever") # Which would call the initialise function
c1.check_equal(c1) # -> True
fluid isle
#

You can actually call the method more directly from the class:

Car.describe(self=mycar)

You just have to pass the self arg manually.

hardy rose
#

yep

proper depot
#

What i'm also not understanding is self itself, is it like a function? Can it be written as self only or can it have any name

hardy rose
fluid isle
#

Also there's nothing preventing you from renaming self, except common convention.

class Car:
    def describe(the_car):
        print(f"It's a {the_car.brand}")

Your editor may scream at you, but it's still functional.

hardy rose
proper depot
#

ahh so self is just used for many examples

hardy rose
#

It's more like the convention

fluid isle
#

If you rename it to something else, you're likely to confuse folks, so you should have a good reason.

hardy rose
#

self for the instance and cls for the class(for classmethod) on the class

fluid isle
#

There is a notable exception in a popular package (ignore this detail, I'm working in it so I find it interesting).
Django's metaclass model magic stuff uses methods that have a cls arg, but those methods are still being called on the class instance, not in a classmethod.

proper depot
#

to my understanding right now

hardy rose
proper depot
#

self is like a variable used inside classes, originally called instance, where you STORE information about whatever the class is about

fluid isle
#

Simpler than that.
self is the instance.

#

You can store data on attributes, call other methods, etc.

#
class Car:
    def __init__(self, brand, fuel_type):
        self.brand = brand
        self.fuel_type = fuel_type
        self.describe()  # Describe yourself now!

    def describe(self):
        print(f"I'm a {self.brand} with fuel type {self.fuel_type}")
proper depot
#

2 stuff that i want to understand

#

what is init with the 2 _ each side

fluid isle
#

It's short for "initialize". In this case it's used as a constructor for a new instance of the class.
If class Car is the blueprint for a car, the data it holds, the methods it has available to act on that data, etc.;
then its __init__ method is the method that builds a new Car.

hardy rose
#

It is call the dunder method, which is to some behaviour python use
In this case, it is initialisation, and you are overriding the default implementation to initialize an object

fluid isle
#

(technically __new__ does that first, but they work together)

proper depot
#

oh wait init and new are different?

hardy rose
#

Yes, but you usually don't use __new__

fluid isle
#

Most often you just have to make an __init__to initialize attributes on the class, maybe call some initial methods.
__new__ actually makes the new instance first. You can override it and change how it behaves, but usually you don't need to.

#

Point is when you call

mycar = Car("Volvo", "diesel")
``` it will call `__new__` to build a new instance of the `Car` class, and your defined `__init__` method to do whatever with those two arguments)
proper depot
#

so init creates a new object, self refers to the instance, and the information inside is what you want stored

#

under it, you store the information such as brand, type

#

simple as that

fluid isle
#

Pretty much ๐Ÿ™‚

proper depot
#

damn okay, what about the second define

#

in this case, def describe

fluid isle
#

That's just a method I made up. You can write any sort of method you like

#

Class instance methods like that one take self as the first argument again, then they do whatever you tell them to do.

proper depot
#

the point of creating a class is to store information that can be later on brought up without having to re create what you have done before

#

right?

fluid isle
#

Think of a class as a type of object. You're defining a new type of data.
For instance, strings are instances of class str. There are methods attached to string objects like .upper() or .lower(), etc.
Same for lists, dicts, tuples, etc.: these are all types, but they are also classes.

So when you define your own class, you are defining a new type, the data it includes, and any methods you want that type to have.

#

You'll find, in fact, that the "functions" str(), list(), tuple(), int(), dict(), set()..., are all classes. When called, they return a new instance of that class.

proper depot
#

damn, they are all classes

#

let's say you have made a new class about planes, and you have done everything, defined the data, stored the information just like you did with the Car class

#

how do you re use it after a long code

#

does my question make sense?

hardy rose
#

For reuse, do you mean create an instance of it? Or what

proper depot
fluid isle
#

Well, this part:

class Car:
    def __init__(self, ...): ...
    def something(self): ...
    def foo(self): ...

This is just the class definition. You define how the class operates.

But this:

mycar = Car(...)
mycar.something()
if one_thing:
    mycar.foo()
``` ...that's actually using a class instance.

Defining a class just defines a class, but it doesn't really do anything else.
You have to then instantiate that class and, well, do stuff with it in your code.
#
my_list_of_cars = [
    Car("BMW", "gas"),
    Car("Toyota", "fuel cells"),
    Car("Honda", "tears of sorrow"),  # /s
    ...
]

You can just make new instances of the same class, and they'd all work independently.

proper depot
proper depot
fluid isle
fluid isle
proper depot
#

My bad if i ask too much questions, sometimes i don't understand it until it gets explained to me step by step

thick wyvernBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.