第八章第3讲:python之访问限制——私有变量

时间:2022-11-22 09:00:14

1. 私有变量是__(双下划线)定义的。

 类中私有变量外部是无法直接访问的;

   可以通过定义方法来获取类中的私有变量或改变私有变量的值。

class Person:
    i = 12345
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def greet(self):
        print("hello world!")
foo = Person('Bela',24)
print(foo.i)
print(foo.name)
print(foo.age)
print(foo.greet())

结果:
12345
Bela
24
hello world!
None
# 定义私有变量,外部无法访问
class Person:
    __i = 12345
    def __init__(self,name,age):
        self.__name = name
        self.__age = age
    def greet(self):
        print("hello world!")
foo = Person('Bela',24)
print(foo.__i)
print(foo.__name)
print(foo.__age)
print(foo.greet())

结果:
Traceback (most recent call last):
  File "C:/Users/lenovo/PycharmProjects/Demo/demo.py", line 10, in <module>
    print(foo.__i)
AttributeError: 'Person' object has no attribute '__i'

 

# 访问私有变量
class Person:
    def __init__(self,name,age):
        self.__name = name
        self.__age = age
    def getInfo(self):
        print("The name is %s,age is %d" % (self.__name,self.__age))
foo = Person('Bela',24)
print(foo.getInfo())

结果:
The name is Bela,age is 24
None

 

# 改变私有变量
class Person:
    def __init__(self,name,age):
        self.__name = name
        self.__age = age
    def getInfo(self):
        return "The name is %s,age is %s" % (self.__name,self.__age)
    def setName(self,name):
        self.__name = name
    def setAge(self, age):
        self.__age = age
foo = Person('Bela',24)
print(foo.getInfo())

foo.setName("Ann")
print(foo.getInfo())

foo.setAge(34)
print(foo.getInfo())

结果:
The name is Bela,age is 24
The name is Ann,age is 24
The name is Ann,age is 34