I’ve spent some time looking for a guide on how to decide how to store data and functions in a python class. I should point out that I am new to OOP, so answers such as:
data attributes correspond to “instance variables”
in Smalltalk, and to “data members” in C++. (as seen in http://docs.python.org/tutorial/classes.html
leave me scratching my head. I suppose what I’m after is a primer on OOP targeted to python programmers. I would hope that the guide/primer would also include some sort of glossary, or definitions, so after reading I would be able to speak intelligently about the different types of variables available. I want to understand the thought processes behind deciding when to use the forms of a, b, c, and d in the following code.
class MyClass(object):
a = 0
def __init__(self):
b = 0
self.c = 0
self.__d = 0
def __getd(self):
return self.__d
d = property(__getd, None, None, None)
a,b, andcshow different scopes of variables. Meaning, these variables have a different visibility and environment in which they are valid.At first, you need to understand the difference between a class and an object. A class is a vehicle to describe some generic behavior. An object is then created based on that class. The objects “inherits” all the methods of the class and can define variables which are bound to the object. The idea is that objects encapsulate some data and the required behavior to work on that data. This is the main difference to procedural programming, where modules just define the behavior , but not the data.
cis now such a instance variable, meaning a variable which lives in the scope of an instance ofMyClass.selfis always a reference to the current object instance the current code is run under. Technically,__dworks the same ascand has the same scope. The difference here is that it is a convention in Python that variables and methods starting with two underscores are to be considered private are are not to be used by code outside of the class. This is required because Python doesn’t have a way to define truely private or proteted methods and variables as many other languages do.bis a simple variable which is only valid inside the__init__method. If the execution leaves the__init__method, thebvariable is going to be garbage collected and is not accessible anymore whilecand__dare still valid. Note thatbit is not prepended withself.Now
ais defined directly on the class. That makes it a so called class variable. Typically, it is used to store static data. This variable is the same on all instances of theMyClassclass.Note that this description is a bit simplified and omits things like metaclasses and the difference between functions and bound methods, but you get the idea…