
Python Classes and Objects - Part 2: Attributes and Methods
What is an attribute?
An attribute is data that belongs to an object. It tells us something about the object.
for example:
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
c1 = Car("Toyota", "Red")
print(c1.brand) # Toyota
print(c1.color) # RedHere, brand and color are attributes.
What is a method?
A method is an action that an object can do. It is written like a normal function, but it is inside a class.
for example:
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
self.speed = 0
def accelerate(self):
self.speed = self.speed + 10
print(self.brand, "is going", self.speed, "km/h")
c1 = Car("Toyota", "Red")
c1.accelerate() # Toyota is going 10 km/h
c1.accelerate() # Toyota is going 20 km/hHere, accelerate is a method.
What is the difference between attribute and method?
- Attribute = data -what the object has
- Method = action -what the object can do
for example, in the Car class:
- brand, color, speed → attributes
- accelerate() → method
Can one method use another method inside a closs?
Yes. Inside a class, one method can call another method it is done using self.
for example:
class Car:
def __init__(self, brand):
self.brand = brand
self.speed = 0
def accelerate(self):
self.speed = self.speed + 10
def drive(self):
self.accelerate()
self.accelerate()
print(self.brand, "speed is now", self.speed)
c1 = Car("Honda")
c1.drive() # Honda speed is now 20Can we give default values to attributes?
Yes. We can give default values inside __init__, so we don't need to pass every value every time.
for example:
class Car:
def __init__(self, brand, color="White"):
self.brand = brand
self.color = color
c1 = Car("Honda")
c2 = Car("Ford", "Blue")
print(c1.color) # White
print(c2.color) # BlueJoin Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments