Once you start using Python, there is no escaping from this word “self”. It is seen in method definitions and in variable initialization. But getting the idea behind it seems somewhat troublesome. Hopefully, at the end of this, you will get an intuitive idea of what “self” is and where you should use it.
But before talking about the self keyword (which is actually not a python keyword or any special literal), first, let’s recall what are class variables and instance variables. Class variables are variables that are being shared with all instances (objects) which were created using that particular class. So when accessed a class variable from any instance, the value will be the same. Instance variables, on the other hand, are variables which all instances keep for themselves (i.e a particular object owns its instance variables). So typically values of instance variables differ from instance to instance.
Class variables in python are defined just after the class definition and outside of any methods:
class SomeClass: variable_1 = “ This is a class variable” variable_2 = 100 #this is also a class variable
Unlike class variables, instance variables should be defined within methods:
Read the rest of this story with a free account.
Already have an account? Sign in
Author
- Hakin9 is a monthly magazine dedicated to hacking and cybersecurity. In every edition, we try to focus on different approaches to show various techniques - defensive and offensive. This knowledge will help you understand how most popular attacks are performed and how to protect your data from them. Our tutorials, case studies and online courses will prepare you for the upcoming, potential threats in the cyber security world. We collaborate with many individuals and universities and public institutions, but also with companies such as Xento Systems, CATO Networks, EY, CIPHER Intelligence LAB, redBorder, TSG, and others.
- LiveSeptember 5, 2024"40 Steps" Satellite Security - Registration for LIVE WORKSHOP IS NOW ON!
- LiveAugust 21, 2024"40 Steps" Game Hacking - Registration for LIVE WORKSHOP IS NOW ON!
- BlogDecember 13, 2022What are the Common Security Weaknesses of Cloud Based Networks?
- BlogOctober 12, 2022Vulnerability management with Wazuh open source XDR