- Get link
- X
- Other Apps
What it is? And How it/each of it works? ATTRIBUTE and CLASS of Determining "Specific" Functionality as it/each of it should be!
Attribute and Method of a Class in Object-Oriented Programming (OOP)
In Object-Oriented Programming (OOP), a class is a blueprint used to create objects. Inside a class, there are two important components: attributes and methods.
1. Attribute (Property / Field)
An attribute is a variable inside a class that stores the data or state of an object.
- It represents what an object has.
- Each object created from the class will have its own values for these attributes.
Example
Class: Car
Attributes:
- brand
- color
- speed
Example in pseudocode:
class Car:
brand = ""
color = ""
speed = 0
Explanation:
- brand → stores the car brand (Toyota, Honda, etc.)
- color → stores the color of the car
- speed → stores the current speed
If an object is created:
myCar = Car() myCar.brand = "Toyota" myCar.color = "Red" myCar.speed = 120
Here, brand, color, and speed are attributes.
2. Method (Function / Behavior)
A method is a function inside a class that defines the behavior or actions of the object.
- It represents what an object can do.
Example
class Car:
def start(self):
print("Car is starting")
def accelerate(self):
print("Car is accelerating")
def brake(self):
print("Car is braking")
Explanation:
- start() → action to start the car
- accelerate() → action to increase speed
- brake() → action to stop the car
Using the object:
myCar = Car() myCar.start() myCar.accelerate()
Here, start() and accelerate() are methods.
3. Simple Analogy
Example: Smartphone
Attributes (data):
- brand
- battery level
- storage
- screen size
Methods (actions):
- turnOn()
- turnOff()
- call()
- sendMessage()
4. Short Definition
- Attribute → variable that stores object data.
- Method → function that defines object behavior.
Summary
In Object-Oriented Programming, a class contains:
- Attributes → describe the state or data of objects
- Methods → define the behavior or actions of objects
Objects created from the class use these attributes and methods.
Comments