In contrast to other programming languages, the Python class mechanism adds classes with at least the new syntax and semantics. It is a hybrid of the class mechanism found in C + + and Modula-3. The Python class provides all the standard features of object-oriented programming: The class inheritance mechanism allows multiple base classes, which can overwrite any method of its base class or class, and the method can invoke a method of the base class with the same name. An object can contain any number and kind of data. For modules, class classifications are the dynamic nature of Python: they are created at run time and can be further modified after creation.
In the C + + terminology, normally class members (including data members) are public (except for private variables and class-local references), and all member functions are virtual. As with Modula-3, it is no different to refer to the members of an object from its methods: The method function is declared as an explicit first argument that represents the object, which is implicitly provided by the call. Like Smalltalk, the classroom itself is the object. This provides the semantics for importing and renaming. Unlike C + + and Modula-3, built-in types can be used as base classes for user extensions. Also, like C + +, most built-in operators with special syntax (operators, subscripts, and so on) can be redefined as class instances.
(lacking universally accepted terminology to discuss classes, I will occasionally use Smalltalk and C + + terminology, I will use the Modula-3 term because its object-oriented semantics are closer to Python than C + +, but I expect few readers to have heard of it.) )
1. In Python, the definition class is by class keyword:
Class ClassName (object): <statement-1> ... <statement-N>
The class name is usually the first word in uppercase, followed by (object) , the concept of which class is inherited from, and the notion of inheritance we will say later, usually, if there is no suitable inheriting class, then the class object is used, which is the class that all classes eventually inherit.
Class Student (object): Pass
Once you have defined the Student class, you can Student create Student an instance from the class by using the class name + () to create the instance:
Student1 = Student ()
You are free to bind attributes to an instance variable, for example, to bart bind an instance to an name attribute:
Tudent1.name = ' Bob ' Student1.score = 99
Because a class can act as a template, you can force a number of attributes that we think must be bound to be filled in when creating an instance. By defining a special __init__ method, when you create an instance, you bind the name score attributes, such as:
Class Student (object): def __init__ (self, Name, score): self.name = name Self.score = Score
Notice that the __init__ first parameter of the method is always the one that self represents the created instance itself, so within the __init__ method, you can bind various properties to it self , because self it points to the created instance itself.
With the __init__ method, when you create an instance, you cannot pass in an empty argument, you must pass in a __init__ parameter that matches the method, but it self does not need to be passed, and the Python interpreter will pass the instance variable in itself:
A function defined in a class is only a little different, that is, the first argument is always an instance variable self , and when called, it is not passed. Besides, there is no difference between a class's method and a normal function, so you can still use the default, variable, and keyword parameters.
Student2 = Student (' Jack ',] print student2.name, Student2.score---------------------------Jack 70
2. Data encapsulation
An important feature of object-oriented programming is data encapsulation. In the above Student class, each instance has its own name and score this data.
Class Student (object): def __init__ (self, Name, score): self.name = name Self.score = Score def print_ Score (self): print '%s--%s '% (Self.name, self.score) Student2 = Student (' Jack ', ') print Student2.name, Student2.scorestudent2.print_score ()------------------------jack--70
Since the Student instance itself has this data, to access the data, there is no need to access the function from outside, you can directly Student define the function to access the data within the class, so that the "data" is encapsulated. The functions of these encapsulated data are Student associated with the class itself, which we call the method of the class. In this way, we look at the class from the outside, just need to Student know that the creation of the instance needs to give name and score , and how to print, are Student defined inside the class, the data and logic is "encapsulated", the call is easy, but do not know the details of the internal implementation.
Another benefit of encapsulation is the ability to Student add new methods to the class
Class Student (object): def __init__ (self, Name, score): self.name = name Self.score = Score def print_ Score (self): print '%s--%s ' percent (Self.name, Self.score) def get_grade (self): if Self.score >= : Return ' A ' elif self.score >=: Return ' B ' else: return ' C ' Student2 = Student (' Jack ', ' d ') print Student2.name, Student2.scorestudent2.print_score () print student2.get_grade ()---------------------------------- Jack 70jack--70b
The class is the template that creates the instance, and the instance is a concrete object, each instance has data that is independent of each other and does not affect each other.
method is the function that binds to the instance, and the normal function is different, the method can directly access the data of the instance;
By invoking the method on the instance, we manipulate the data inside the object directly, but need not know the implementation details inside the method;
Unlike static languages, Python allows you to bind any data to an instance variable, which means that for two instance variables, although they are different instances of the same class, the variable names you have may be different.
3. Access Restrictions
Inside class, you can have properties and methods, and external code can manipulate the data by invoking the instance variable directly, thus hiding the complex logic inside.
However, from the previous definition of the student class, the external code is free to modify the properties of an instance name score :
If you want the internal properties to be inaccessible externally, you can add the name of the property with two underscores __ , and in Python, the variable name of the instance __ becomes a private variable (private), which can only be accessed internally and cannot be accessed externally, so We changed the Student class:
Class Student (object): def __init__ (self, Name, score): self.__name = name Self.__score = Score def Print_score (self): print '%s--%s '% (Self.__name, Self.__score)
After the change, there is no change to the external code, but there is no external access 实例变量.__name and 实例变量.__score
STD1 = Student (' Mink ', ') std1.__name---------------------------------Traceback (most recent call last): line 320 , in <module> std1.nameattributeerror: ' Student ' object has no attribute ' name '
What if I want to allow external code to modify score? You can add methods to the Student class set_score :
Class Student (object): ... def set_score (self, score): Self.__score = Score
The original kind of direct through .score = 70 the Student2 can also be modified Ah, why to define a method big trouble? Because in a method, you can check the parameters to avoid passing in invalid arguments:
Class Student (object): ... def set_score (self, score): if 0 <= score <=: self.__score = score else: raise ValueError (' bad Score ')
It is important to note that in Python, the variable name is similar, which starts with a double underscore, and ends with a double underscore, which is a special variable that __xxx__ can be accessed directly, not a private variable, so __name__ __score__ the variable name cannot be used.
There are times when you see an instance variable name that starts with an underscore, such as an _name instance variable that can be accessed externally, but, as you see in the rules, when you look at a variable like this, the meaning is, "although I can be accessed, please treat me as a private variable and don't feel free to access it."
is an instance variable that starts with a double underscore not necessarily externally accessible? Actually, it's not. cannot be accessed directly __name because the Python interpreter __name has changed the variable so that it _Student__name can still be accessed by _Student__name accessing the __name variable: But it is highly recommended that you not do this because different versions of the Python interpreter might __name Change to a different variable name.
Python-Classes and instances