Skip to content
Sign upLog in
← Back to Community

Class vs Function-(Python)

Profile icon
DavidClone

Why does class exist when we have functions? I know how to create a class but I don't understand why we need to use class.

Answered by ash15khng [earned 5 cycles]
View Answer
Voters
Profile icon
DavidClone
Comments
hotnewtop
Profile icon
ash15khng

Functions are basically a way to reuse code. They can only store what you want to do with it.
Classes can store multiple functions and variables in them. You can also create instances of classes which can store different things.
An example:

class Car: wheels = 4 def __init__(self, colour): self.colour = colour car1 = Car("red") car2 = Car("blue") print(car1.colour) # prints "red" print(car2.colour) # prints "blue" print(car1.wheels) # prints 4 print(car2.wheels) # prints 4 car2.wheels = 18 print(car1.wheels) # prints 4 print(car2.wheels) # prints 18

The class Car has 2 instances: car1 and car2, and it has a two variables, colour and wheels. A function wouldn't be able to store all this.

Profile icon
DavidClone

@ash15khng
Thanks this really helped.

Profile icon
ash15khng

@DavidClone
No problem!

Profile icon
Masy

Classes are instances and functions are a way to do things

Profile icon
Geocube101

Classes can be useful for creating instances and applying values to an object
Functions are reusable pieces of code used for doing stuff
Classes are also reusable, but can apply their values to a variable
I use them for when I want a set of available functions for a variable instance.
Before I knew how to make classes, I created a set of functions that did different things to lists. The object itself was never modified, but a copy was made and returned. With classes, I could drop a parameter (as I had a parameter for the array) and modify the original object.

Profile icon
DavidClone

@Geocube101
This helped "unconfuse" me! Thanks!