The study of access restriction in Python(20170920) 访问限制

The study of access restriction in Python(20170920) 访问限制

class per_info(object):
def init(self, name, age, gender):
self.__name = name
self.__age = age
self.__gender = gender
# the three parameters are private parameters
# only can be get in inner
# can’t be get on outer
def show_info(self):
return (‘%s:%d,%s’ % (self.__name, self.__age, self.__gender))

how to get the private parameters

def get_name_age_gender(self):
    return self.__name, self.__age, self.__gender

how to modify the private parameters

def modify_parameters(self, name, age, gender):
    self.__name = name
    self.__age = age
    self.__gender = gender
    return self.__name, self.__age, self.__gender

person_1 = per_info(‘yuhanyu’, 22, ‘male’)
print(person_1.show_info()) # True

print(person_1.__name) # False

print(person_1.get_name_age_gender()) # True
print(person_1.modify_parameters(‘amu’, 23, ‘female’))

how to get the Instance variable(实例变量)

print(person_1._per_info__name)

but this way should not often use

需要注意的是,在Python中,变量名类似xxx的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用namescore这样的变量名

有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”

你可能感兴趣的:(python)