Skip to content
Sign UpLog In
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
1

Class vs Function-(Python)

DavidClone
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.

3 years ago
You are viewing a single comment. View All
1
ash15khng
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.

3 years ago
1
DavidClone
DavidClone

@ash15khng
Thanks this really helped.

3 years ago