Start with the most basic class. Employee defines an employee’s attributes and methods. Create two objects from it (emp1, emp2), then read their data.
class Employee:
# constructor
def __init__(self, name, role, salary, city):
self.name = name
self.role = role
self.salary = salary
self.city = city
def getInfo(self):
print(f'name:{self.name}, role:{self.role}, salary:{self.salary}, city:{self.city}')
emp1 = Employee('Peter', 'Developer', 3000, 'HK')
emp2 = Employee('Mary', 'Manager', 5000, 'HK')
print(emp1.name)
emp1.getInfo()output:
Peter name:Peter, role:Developer, salary:3000, city:HK
- __init__ is the constructor. It runs automatically when you create an object and sets the attributes.
- A class is the blueprint (definition) for objects. Employee above is the blueprint; emp1 and emp2 are the objects (instances) it produces.
- The two key parts of a class: attributes (each instance keeps its own, class-level ones are shared) plus methods.
- Variables come in two kinds: class variables (shared by the whole class) vs instance variables (each object has its own copy).
- Methods come in two kinds: class methods (use cls, no instance needed) vs instance methods (use self).
- Call direction: an instance can call class-level stuff, but the class can’t directly call instance-level stuff.
