After those days drilling on the SVM project with Python, I grasped a little thoughts on Python class. Share with you here.
- ‘self’ statement:
‘self.variable’ states that variable is a global defined member of that class, which can be used in any methods of this class. Otherwise, without the ‘self’ prefix, the use of the variable is only confined within its own method.
self. var = 0; # defines a variable that can be used throughout all methods within class (global var)
var = 0; # defines a variable that can be used only within the method (local var)
- __ini__ function
The function is used for initializing the values of some private variables that will be used later. In Python, It functions like the combination of the initial declaration and the constructor function in C++, where they are done via two steps.
For example, for a class named Person, in C++ we initialize a Person-class object as follows,
class Person ()
string name; int age;
name = 'unknown';
age = 0;
But in Python, two steps are integrated when defining the constructor function __ini__ (the constructor function also defines the private paramters), which is also a reason for the ‘self’ parameter:
self. name = 'unknown'
self. age = 0
Of course, the __ini__ function can also exert the function of external parameter transportation to the class, like,
def __ini__(self, exname, exage):
self. name = exname
self. age = exage
Here the external parameters exname and exage is transported to the class object.