chzhiyi / -KnowledgeShare

6 stars 1 forks source link

20190326 - 面向对象中的变量类型 - qiaosong #40

Open chzhiyi opened 5 years ago

chzhiyi commented 5 years ago

普通变量

  • 外部代码可以修改内部属性
    
    class Student(object):
    def __init__(self, name, score):
    self.name = name
    self.score = score

def print_var(): bart = Student('Bart Simpson', 59) print(bart.score) bart.score = 100 #修改内部属性Student.name print(bart.score)

print_var()


### 私有变量
>+  `以两个下划线__开头的变量`,叫私有变量(private),如__name;只有内部能访问,外部不能访问。
>+  外部访问`实例变量.__变量名称`会报错,如AttributeError: 'Student_not_modified' object has no attribute '__name'。通过访问限制的保护,外部代码不能随意修改对象内部的状态
>+  可以通过在内部代码中定义额外的方法,来返回变量的值;或修改变量的值
>+  在"普通变量"中可以通过bart.score=100来直接修改变量,为什么再要额外定义一个方法来修改呢?在方法中,可以对参数做检查,避免传入无效的参数
>+  【此方法不推荐】虽然不能通过Student_not_modified.__name直接访问,但可以通过_Student_not_modified__name来访问,从而获得__name的值;因为python解释器对外把__name改成了_Student_not_modified__name。
```python
class Student_not_modified(object):

    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_score(self):
        print('%s: %s' % (self.__name, self.__score))

    def get_name(self):
        return self.__name

    def get_score(self):
        return self.__score

    def set_name(self, name):
        self.__name = name

    def set_score(self, score):
        if 0 <= score <= 100:
            self.__score = score
        else:
            raise ValueError('bad score')  

def print_var_not_modify():
    bart = Student_not_modified('Bart Simpson', 59)
    print(bart.get_name())  #注释掉Student_not_modified.get_name方法, 'Student_not_modified' object has no attribute '__name'; 

def print_set_score():
    bart = Student_not_modified('qiaosong', 90)
    bart.set_score(120)  #修改score的值,会判断传入的参数是否有效

def print_special():
    bart = Student_not_modified('qiaosong', 90)
    print(bar._Student_not_modified__name)

print_var_not_modify()
print_set_score()
print_special()

特殊变量

  • 以双下划线开头,并且以双下划线结尾的,__xxx__,如__name__、__score__
  • 是可以直接访问的

其它变量

  • 以一个下划线_开头,如_name

  • 虽然我可以被访问,但请把我视为私有变量,不要随意访问

  • 如_Student_not_modified__name

参考网址

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318650247930b1b21d7d3c64fe38c4b5a80d4469ad7000