python学习41:类的公有变量和私有变量

 student1是公有变量,可以在函数外修改变量,比如我写的right部分;

student2是私有变量,但是不可以在函数外修改变量,比如我写的wrong部分;

这里的私有变量,虽然可以复制,但是修改不了,打印结果,还是之前的赋值。

student3是私有变量,但是可以在函数外修改变量,比如我写的can change 3部分。

公有变量和私有变量的表面区别,就是在变量前加了两个下划线__。

class Student1(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score

    def PrintScore(self):
        print('%s: %s' % (self.name,self.score))


s1 = Student1('python','80')
s1.PrintScore()
## right
print(s1.name)
print(s1.score)
##
## can change 3
s1.name = 'c'
s1.score = '95'
s1.PrintScore()
## 
print('----------------------------------')


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

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

s2 = Student2('java','30')
s2.PrintScore()
## wrong
##print(s2.__name)
##print(s2.__score)
##
## can't change
s2.__name = 'shell'
s2.__score = '85'
s2.PrintScore()
##
print('----------------------------------')


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

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

    ## additional parts
    def GetName(self):
        return self.__name
    def GetScore(self):
        return self.__score

    def SetName(self,name):
        self.__name = name
    def SetScore(self,score):
        self.__score = score
    ##

s3 = Student3('java',30)
s3.PrintScore()

## can change
print(s3.GetName())
print(s3.GetScore())

s3.SetName('shell')
s3.SetScore('85')
s3.PrintScore()

测试结果:

=========================== RESTART: E:/object.py ===========================
python: 80
python
80
c: 95
----------------------------------
java: 30
java: 30
----------------------------------
java: 30
java
30
shell: 85

 

你可能感兴趣的:(python学习之路)