Attributes and Methods
Attributes and Methods
Example:
class Employee:
# This attribute is common across all instances of this
class
numberOfEmployees = 0
employeeOne = Employee()
employeeTwo = Employee()
Employee.numberOfEmployees += 1
print(employeeOne.numberOfEmployees)
print(employeeTwo.numberOfEmployees)
# Output => 1, 1
# Since numberOfEmployees was created as a class
attribute, we incremented it to 1 by making use of its class
name. This value has been reflected across objects
employeeOne and employeeTwo.
3. What is an instance attribute ?
An attribute that is specific to each instance of a class is
called an instance attribute.
Instance attributes are accessed within an instance method
by making use of the self object.
Syntax:
class className:
def methodName(self):
self.instanceAttribute = value
Example:
class Employee:
def employeeDetails(self, name):
# name is the instance attribute
self.name = name
Example:
class Employee:
def setName(self, name):
self.name = name
employee = Employee()
employee.setName('John')
# The above statement is inferred as
Employee.setName(employee, 'John') where the object
employee is taken as the self argument.
# In the init method when we say self.name, Python actually
takes it as employee.name, which is being stored with the value
John.
5. What are methods ?
A function within a class that performs a specific action is
called a method belonging to that class.
Methods are of two types: static method and instance
method
Example:
class Employee:
# employeeDetails() is the instance method
def employeeDetails(self, name):
self.name = name
Example:
class Employee:
numberOfEmployees = 0
@StaticMethod
def updateNumberOfEmployees():
Employee.numberOfEmployees += 1
employeeOne = Employee()
employeeTwo = Employee()
employeeOne.updateNumberOfEmployees()
employeeTwo.updateNumberOfEmployees()
print(Employee.numberOfEmployees)
Example:
class Employee:
numberOfEmployees = 0
def printNumberOfEmployees(self):
print(Employee.numberOfEmployees)
employee = Employee()
# Modify class attribute using dot operator
Employee.numberOfEmployees += 1
# Call the instance method using dot operator
employee.printNumberOfEmployees()
Example:
class Employee:
def __init__(self):
print("Welcome!")
employee = Employee()
# This would print Welcome! since __init__ method was
called on object instantiation.