Table of Contents
About Python Classes, Objects, Attributes & Methods
A Class is like an object constructor, a template for creating objects.
A class defines the general characteristics of a thing (Object), which include the thing’s characteristics (it’s attributes, fields or properties) and the thing’s behaviors (methods, meaning the things it can do).
An Object is a particular instance of a Class.
The set of values of the attributes of a particular object its called its state.
A class instance (object) can have attributes(fields or properties) attached to it for maintaining its state. Attributes store information about the instance.
Class instances (objects) can also have methods (defined by its class) for modifying its state. The behavior of an object is defined by its methods.
Everything in Python is an object, even numbers or functions! With its properties and methods.
Python classes provide all the standard features of Object-Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Read more about Python classes
Python dir()
The dir() function returns all available properties and methods of the specified object, without the values.
>>> x = 'hello' >>> type(x) <class 'str'> >>> dir(x) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>>
The methods with underscores are used by Python itself!
How to create a class in Python?
To create a class, use the keyword “class” followed by the name of the class.
Usually, the first argument to any of the methods of a class, is the self argument.
The self argument refers to the object itself, the instance in which the method is being called. It’s kind of like this keyword in JavaScript.
class Vehicle: vtype = 'car' #You don't have to name this self, but most tends to call this self. def start(self): print('The',self.vtype, 'started') car1 = Vehicle() car1.start() #The type() function returns the type of the specified object print('\nType', type(car1)) #The dir() function returns all properties and methods of the specified object, without the values. print('\nMethods', dir(car1)) //The car started Type: <class '__main__.Vehicle'> Methods: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'start', 'vtype']
Object Life Cycle
Life Cycle: Objects are created, used and discarded
Constructors in Python
A constructor is a special method used for instantiating an object, assigning values to the data members of the class when an object of the class is created.
The __init__() method is always called when an object is created.
Destructors in Python
In opposite with the constructor, a destructor is a special method used to destroy the object and perform the final clean up.
In Python, destructors are needed much less, because Python has a garbage collector that handles memory management.
The constructor and destructor are optional.
class Vehicle: vtype = 'car' #You don't have to name this self, but most tends to call this self. def start(self): print('The',self.vtype, 'started') def __init__(self): print('The constructor was called') def __del__(self): print('The destructor was called') car1 = Vehicle() //The constructor was called The destructor was called
Constructors cand have additional parameters
class Vehicle: vtype = '' def start(self, x): self.vtype = x print('The', self.vtype, 'started') vh1 = Vehicle() vh1.start("car") //The car started
The destructor is called whether if you reassign the variable or the program ends.
class Vehicle: vtype = 'car' #You don't have to name this self, but most tends to call this self. def start(self): print('The',self.vtype, 'started') def __del__(self): print('The destructor was called') car1 = Vehicle() car1 = 3 print(car1) // The destructor was called 3
How to create multiple instances of the same class?
In Python, multiple objects or instances of a class can be created just as you declare multiple variables of the same type.
Each instance has its own copy of the instance variables.
Object Inheritance
Inheritance is the capability of a class to derive or inherit all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
The child class has all the capabilities of the parent class and some more.
class Vehicle: vtype = '' def start(self, x): self.vtype = x print('The', self.vtype, 'started') #Auto class extends Vehicle class class Auto(Vehicle): nun = 2 def open(self, x): self.num = 4 print(self.num, 'doors were opened') auto1 = Auto() auto1.start("car") auto1.open(4) //The car started 4 doors were opened
Static Methods in Python
A Static method can be called without creating an object or instance.
In contrast, if you want to call non-static methods, you’ll have to create an object.
How to define a static method?
Add the keyword @staticmethod above it to make it static.
class Vehicle: vtype = '' def start(self, x): self.vtype = x print('The', self.vtype, 'started') @staticmethod def cleanVehicle(): print('Cleaning the vehicle') auto1 = Vehicle() auto1.cleanVehicle() //Cleaning the vehicle
Visibility for Objects and Classes in Python
Python has no such visibility restrictions. All attributes and methods are visible to everyone.
Differences between Python classes and PHP classes
- Python has no such visibility restrictions. All attributes and methods are visible to everyone. Unlike In PHP each property of a class can have one of three visibility levels (Public, Private, Protected). Read more here about Objects Property Visibility in PHP
Hello there!
I hope you find this post useful!I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.
If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!