Python day 8 (1) class and instance (2), pythonday
I. Classes and Instances
1. The most important concepts of object orientation are Class and Instance. Classes are abstract templates. Instances are specific "objects" created based on classes. Each object has the same method, but its data may be different.
2 in Python, the class is defined throughclassKeywords:
class Student(object): pass
classFollowed by the class name, that isStudentThe class name is usually a word starting with an upper case, followed(object)Indicates the class from which the class is inherited. We will talk about the concept of inheritance later. Normally, if there is no suitable inheritance class, useobjectClass.
3 DefinedStudentClass, you canStudentClass createdStudentThe instance is created using the class name +:>>> bart = Student()
4. You can freely bind attributes to an instance variable, suchbartBind onenameAttribute:>>> bart.name = 'Bart Simpson'
5. When creating an instance, you can forcibly enter some attributes that we think must be bound. By defining a special__init__When creating an instancename,scoreAnd other attributes:
class Student(object): def __init__(self, name, score): self.name = name self.score = score
Note: The special method "_ init _" has two underlines !!! 6
__init__The first parameter of the method is always
self, Indicates the created instance. Therefore
__init__Internal method, you can bind various attributes
selfBecause
selfPoint to the created instance itself. With
__init__When you create an instance, you cannot enter an empty parameter.
__init__Method matching parameters,
selfYou do not need to upload the instance variables. The Python interpreter will upload the instance variables as follows:
>>> bart = Student('Bart Simpson', 59)7. Compared with a common function, the function defined in the class is only a little different, that is, the first parameter is always an instance variable.
selfAnd you do not need to pass this parameter during the call. In addition, class methods are no different from common functions. Therefore, you can still use default parameters, variable parameters, keyword parameters, and named keyword parameters. Ii. Data encapsulation (an important feature of Object-Oriented Programming) 1.
StudentClass internally defines the function to access data. In this way, the "data" is encapsulated. The functions that encapsulate data are
StudentClasses are associated. We call them class methods. 2. Define a method, except that the first parameter is
selfAnd other functions. To call a method, you only need to call it directly on the instance variable,
selfNo need to pass. Other parameters are passed in normally. 3. access restriction 1 is inside the Class and can have attributes and methods, while external code can directly call the method of instance variables to operate data, thus hiding the complicated internal logic. However, external code can freely modify the object of an instance. 2. If you want to prevent internal properties from being accessed externally, you can add two underscores (_) before the attribute name.
__In Python, if the variable name of an instance is
__At the beginning, it becomes a private variable, which can only be accessed internally and cannot be accessed externally. Therefore, we change the Student class to the following:
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 modification, there is no change to the external code, but it is no longer accessible from the externalInstance variable. _ nameAndInstance variable. _ score. This ensures that the external code cannot modify the internal state of the object at will, so that the code is more robust through access restriction protection.
3. If the external code needs to obtain internal attributes, you can add the Student classget_nameAndget_scoreThis method.
def get_name(self): return self.__name def get_score(self): return self.__score
What if I want to allow external code to modify the score? You can add Student classes.set_scoreMethod:
def set_score(self, score): self.__score = score
4
A in Python, the variable name is similar__xxx__Is a special variable that begins with Double underline and ends with Double underline. Special variables can be directly accessed, not private variables.
B is the name of an instance variable starting with an underscore, such_nameSuch instance variables can be accessed outside, but, according to the conventions, when you see such variables, it means, "Although I can be accessed, please treat me as a private variable and do not access it at will ".
Instance variables starting with a double underscore (_) may not be accessed externally. Cannot be accessed directly__nameThe reason is that the Python Interpreter__nameVariable changed_Student__name, So you can still use_Student__nameTo access__nameVariable. However, this is not recommended because different versions of the Python interpreter may__nameChange to different variable names.
D
Bart = Student ('bart Simpson ', 59) >>> Bart. get_name () 'bart Simpson '>>> Bart. _ name = 'new name' # Set the _ Name variable. >>> Bart. _ name 'new name'
On the surface, the external code is successfully set__nameVariable, but in fact this__nameVariable and class internal__nameThe variable is not a variable! Internal__nameThe variable has been automatically changed by the Python interpreter._Student__nameAnd external codebartAdded__nameVariable. Try it without belief:
>>> Bart. get_name () # get_name () internal return self. _ name 'bart Simpson'