Classes and Objects
Last updated
Last updated
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.
Classes are created by keyword class
Attributes are the variables that belong to a class
Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute
The self
parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it.
If we have a method that takes no arguments, then we still have to have one argument.
it's similar to constructors in C++ and Java
Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
Instance variables are for data, unique to each instance and class variables are for attributes and methods shared by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or method with self whereas class variables are variables whose value is assigned in the class.
You can modify properties on objects like this:
You can delete properties on objects by using the del
keyword:
You can delete objects by using the del
keyword:
class
definitions cannot be empty, but if you for some reason have a class
definition with no content, put in the pass
statement to avoid getting an error.