#๐ Classes
89 messages ยท Page 1 of 1 (latest)
@proper depot
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.
That's imagine you need to represent a Car
yes
What in the car you can observe(attribute/properties), and what the car can do
You only have taken the input, but never stored them
isn't def as in defining them and then __ innit __ the way to store them?
No, __init__ is just define how you receive the input
How does it work then?
Like Car("Brand", "Type data whatever")
You have the self, which is the instance of the class
You store them in the instance
then why did this guy do it like this?
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
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
then why did this guy do it like this?
Like what? Noone here is going to watch a 6 minute video
Can you share the code in question. As text
https://prod.liveshare.vsengsaas.visualstudio.com/join?7F21CDB0963BF1BEC9077AB073E672B2449D
Here a read/write sync code editor
Build with Visual Studio Code, anywhere, anytime, entirely in your browser.
Just share it as text please instead of relying on a join that you need to approve
It is just for explaining where he could edit the same thing at the same time
Either share your code as Discord text (properly formatted) or use a website like https://paste.pythondiscord.com/, https://pastebin.com/, or https://www.toptal.com/developers/hastebin
dawg what code
let me and the other guy talk
well what makes it different from it having an instance or not?
since the way you just wrote it has no instance
Oh, that one is just to get the instance
oh yeah i know, i'm in the middle of learning python and now i'm at classes trying to go to file i/o after
trying to understand how classes originally work
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
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()
:white_check_mark: Your 3.13 eval job has completed with return code 0.
I'm a Volvo with fuel type diesel
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.
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
You can actually call the method more directly from the class:
Car.describe(self=mycar)
You just have to pass the self arg manually.
yep
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
recommend modification to but put self= but pass as the first positional argument because that what python care
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.
Any name, just the first positional argument
ahh so self is just used for many examples
It's more like the convention
If you rename it to something else, you're likely to confuse folks, so you should have a good reason.
self for the instance and cls for the class(for classmethod) on the class
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.
to my understanding right now
I think there is a even longer form but I forgot what it is
self is like a variable used inside classes, originally called instance, where you STORE information about whatever the class is about
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}")
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.
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
(technically __new__ does that first, but they work together)
oh wait init and new are different?
Yes, but you usually don't use __new__
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)
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
Pretty much ๐
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.
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?
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.
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?
For reuse, do you mean create an instance of it? Or what
Well the point of making classes is to store objects, data so you wouldn't have to do the work all again, if you needed the class at some point in the code, how do you use it? LIke how do you print it
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.
Ohh, so you define everything in the class, and if you want to use it again, you just create a variable for the class and use it
wait lists can be used like this? multiple lines, now just in the same line?
Your class definitions defines how the class operates, what it does with the data you give it.
When you make a new instance of that class, you give that instance some data, that class instance stays around in memory somewhere, you can pass that instance around like just any other piece of data.
Yes, that's pretty common, especially for very large lists, or tuples, or sets, or function signatures...
My bad if i ask too much questions, sometimes i don't understand it until it gets explained to me step by step
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.