You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

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.

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)


To create an object of the class Employee and use its methods, you can do the following:

employee = Employee("John Doe", 30, 50000)
employee.display_employee_info()


Below is another example

<?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

?>



  • No labels