Python Day 8 (1) Classes and instances (2)

Source: Internet
Author: User

One: Classes and instances

1 The most important concepts of object orientation are classes (class) and instances (Instance), and classes are abstract templates. An instance is a specific "object" created from a class, each of which has the same method, but the data may be different.

2 in Python, the definition class is by class keyword:

class Student(object):    pass

classfollowed by the class name, that is, the Student class name is usually the beginning of the word, followed by, the class is (object) to indicate which class inherits from, the concept of inheritance we will say later, usually, if there is no suitable inheritance class, you use the object class, this is all classes will eventually inherit the class.

3 Student when a class is defined, it is possible to create an instance from a Student class Student by using the class name + () to create the instance:>>> bart = Student()

4 You are free to bind a property to an instance variable, for example, to bart bind an instance to an name attribute:>>> bart.name = ‘Bart Simpson‘

5 When creating an instance, you can force some of the attributes that we think must be bound to be filled in. 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
Note: There are two underscores before and after the special method "__INIT__"!!! __init__ The first parameter of the 6 method is always a self representation of the created instance itself, so that within the __init__ method, various properties can be bound to 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 parameter, you must pass in the __init__method to match the parameters, but selfNo need to pass, the Python interpreter will pass the instance variable in itself: >>> bart = Student(‘Bart Simpson‘, 59)7 a function defined in a class is only a little different than a normal function, that is, the first argument is always an instance variable self , and when called, it is not passed. In addition, there is no difference between a class's method and a normal function, so you can still use default, variable, keyword, and named keyword parameters. Two: Data encapsulation (an important feature of object-oriented programming)1 defines the Student function that accesses the data directly 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. 2 To define a method, except for the first argument self , the other is the same as a normal function. To invoke a method, you only need to call it directly on the instance variable, except that the other parameters are passed in self normally.  Three: Access restrictions 1 within class, you can have properties and methods, while external code can manipulate data by invoking the method of the instance variable directly, thus hiding the complex logic inside. But external code is also free to modify the zodiac of an instance. 2 If you want internal properties to be inaccessible externally, you can add two underscores to the name of the property __, in Python, the variable name of the instance __At the beginning, it becomes a private variable (private), only the internal can be accessed, external cannot access, so we change 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 it cannot be accessed from outside 实例变量.__name 实例变量.__score . This ensures that external code cannot arbitrarily modify the state inside the object, so that the code is more robust through access-restricted protection.

3 If external code is to get internal properties, you can add get_name get_score such methods to the student class.

def get_name(self):        return self.__name def get_score(self): return self.__score

What if I want to allow external code to modify score? You can add additional methods to the student class set_score :
 def set_score      4  
A in Python, the variable name is like __xxx__ , which starts with a double underscore and ends with a double underscore, is a special variable , a special variable is directly accessible, not a private variable
_name , This instance variable can be accessed externally, but, as you can see by the rules, when you look at such a variable, it means, "although I could be accessed, please treat me as a private variable and don't feel free to access it." An instance variable that starts directly with a
__name cannot be accessed directly because the Python interpreter has changed the __name variable to _student__name , so you can still use the _ Student__name to access the __name variable. However, this is not recommended because different versions of the Python interpreter may change the __name to a different variable name.
d
 bart = Student(‘Bart Simpson‘, 59)>>> bart.get_name()‘Bart Simpson‘>>> bart.__name = ‘New Name‘ # 设置__name变量!>>> bart.__name‘New Name‘

On the surface, the external code "succeeds" in setting the __name variable, but actually the variable __name and the variable inside the class are __name not a variable! The internal __name variables have been automatically changed by the Python interpreter _Student__name , and the external code bart adds a new __name variable. Try not to believe:

>>> bart.get_name() # get_name()内部返回self.__name‘Bart Simpson‘



Python Day 8 (1) Classes and instances (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.