In below example, the class Employee has three instance variables name, age, and salary. The __init__ method is a special method in Python that is automatically called when an object of the class is created. This method sets the initial values of the instance variables. The display_employee_info method prints the values of the instance variables.
Code Block |
---|
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def display_employee_info(self):
print("Name:", self.name)
print("Age:", self.age)
print("Salary:", self.salary)
|
...
Code Block |
---|
employee = Employee("John Doe", 30, 50000) employee.display_employee_info() |
Below is another example
Code Block |
---|
<?php
class Car {
public $make;
public $model;
public $year;
public function getMakeAndModel() {
return $this->make . ' ' . $this->model;
}
}
$car = new Car();
$car->make = "Toyota";
$car->model = "Camry";
$car->year = 2020;
echo $car->getMakeAndModel();
// Output: Toyota Camry
?> |