Attributes & Methods
Shopping Cart
- Users can add different items to their shopping cart and checkout.
- The total value of the cart should be more than a minimum amount (Rs. 100/-) for the checkout.
- During Offer Sales, all users get a flat discount on their cart and the minimum cart value will be Rs. 200/-.
Attributes
Broadly, attributes can be categorized as
- Instance Attributes
Class Attributes
Instance Attributes
Attributes whose value can differ for each instance of class are modeled as instance attributes.
Ex: Items in Cart
Class Attributes
Attributes whose values stay common for all the objects are modelled as Class Attributes.
Ex: Minimum Cart Bill, Flat Discount
Accessing Instance Attributes
Code
Output
Instance attributes can only be accessed using instance of class.
Self
Code
Output
Accessing Using Self
Code
Output
Accessing Using Object
Code
Output
Accessing Using Class
Code
Output
Accessing Class Attributes
Example 1
Code
Output
Example 2
Code
Output
Updating Class Attribute
Code
Output
Method
Broadly, methods can be categorized as
- Instance Methods
- Class Methods
- Static Methods
Instance Methods
Instance methods can access all attributes of the instance and have self as a parameter.
Example 1
Code
Output
Example 2
Code
Output
Class Methods
Methods which need access to class attributes but not instance attributes are marked as Class Methods. For class methods, we send
Code
Output
We will learn more about decorators in upcoming sessions.
Accessing Class Method
Code
Output
Static Method
We might need some generic methods that don’t need access to either instance or class attributes. These type of methods are called Static Methods.
Usually, static methods are used to create utility functions which make more sense to be part of the class.
We will learn more about decorators in upcoming sessions.
Code
Output
Overview of Instance, Class & Static Methods
Instance Methods | Class Methods | Static Methods |
---|---|---|
self as parameter | cls as parameter | No cls or self as parameters |
No decorator required | Need decorator @classmethod | Need decorator @staticmethod |
Can be accessed through object(instance of class) | Can be accessed through class | Can be accessed through class |