您的当前位置:首页python伪私有属性的理解

python伪私有属性的理解

2024-07-17 来源:乌哈旅游

1、说明

(1)确保定义类别中的属性(类别属性和实例属性)名称是唯一的,即使是同名属性,也能区分属于哪个类别中的定义属性。

(2)在属性名称前面添加__双下划线,后面不添加下划线,py会将此属性转换为_className__attrName。

(3)可视为私有属性,即对外暴露的属性名称不再是定义的属性名称,而是_className__attrName。

(4)使用伪属性是为了保证唯一性,防止不同子类在多继承过程中命名相同而产生冲突。

2、实例

## private.py
class Person:
    __template_name = "person instance template name"
 
    def __init__(self,name):    
        self.__name = name      ## __name 属于Person类,
 
    def get_name(self):
        return self.__name
 
    @staticmethod
    def get_template_name():
        return Person.__template_name
 
>>> p = Person("keithl")
>>> print(p.get_name())
keithl
 
>>> print(p._Person__name)
keithl
 
>>> print(p.__name)
AttributeError: 'Person' object has no attribute '__name'
 
>>> print(dir(p))

以上就是python伪私有属性的理解,希望对大家有所帮助。更多Python学习指路:

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

显示全文