5.2, access restrictions

Within Class, you can have properties and methods, and the external code data may be operated by direct calling instance variable, so that it hides the complexity of the internal logic.

However, from the point of view of the Student class defined above, external code is free to modify one example name, scoreattributes:

 

 If you want the internal attributes are not externally accessible, you can put before the name of the property plus two underscores __, in Python, the instance variable name if the __beginning, it becomes a private variable (private), only internal access to, can not access external

 

You can not access the instance variables from external .__ name and instance variables .__ score

This ensures that external code can not be free to modify the internal state of an object, such protection through access restrictions, code more robust.

But if the external code to get the name and score how to do? Student class to be increased get_nameandget_score a method:

 

class Student(object):
    def __init__(self,name,score):
        self.__name=name
        self.__score=score
    
    def get_name(self):
        return self.__name
    def get_score(self):
        return self.__score
        
    def get_grade(self):
        if self.__score>=90:
            return 'A'
        elif self.__score>=60:
            return 'B'
        else:
            return 'C'
    
def print_score(std):
    print('%s:%s   %s'%(std.get_name(),std.get_score(),std.get_grade()))
    
liuqi=Student('liuqi',100)
lijie=Student('lijie',50)
print_score(liuqi)
print_score(lijie)

 

By .score can still change the data. However, this data can not be detected, it may pass invalid data

If you have to allow external code modifications score how to do? Student class can give increased set_scoremethods:

 

class Student(object):
    def __init__(self,name,score):
        self.__name=name
        self.__score=score
    
    def get_name(self):
        return self.__name
    def get_score(self):
        return self.__score
    
    def set_score(self,score):
        if 0<=score<=100:
            self.__score=score
        else:
            raise ValueError('bad score')
        
    def get_grade(self):
        if self.__score>=90:
            return 'A'
        elif self.__score>=60:
            return 'B'
        else:
            return 'C'
    
def print_score(std):
    print('%s:%s   %s'%(std.get_name(),std.get_score(),std.get_grade()))
    
liuqi=Student('liuqi',95)
lijieStudent = ( ' Lijie ' , 50 ) 
print_score (liuqi) 
print_score (Lijie)

 

 

 

 

 In fact, this is the addition of a variable __name, the actual internal variables have become _Student_name, so there is no change

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/soberkkk/p/12633710.html
5.2
5.2