python中私有属性和私有方法

Python对于类的成员没有严格的访问控制限制,这与其他面相对对象语言有区别。关于私有属性和私有方法,有如下要点:

  • 1、通常我们约定,两个下划线开头的属性是私有的(private)。其他为公共的(public);
  • 2、类内部可以访问私有属性(方法);
  • 3、类外部不能直接访问私有属性(方法);
  • 4、类外部可以通过 ”_类名__私有属性(方法)名“ 访问私有属性(方法)

定义私有属性/方法

class Demo:
    __price = 25.8

    def __init__(self, u_name, u_age):
        self.uname = u_name
        self.__uage = u_age

    def __age(self):
        print("这是私有方法")
        print("调用共有属性:", self.uname)
        print("调用私有属性:", self.__uage)
        print("调用私有类属性:", self.__price)

    def name(self):
        print("这是公有方法")
        print("调用共有属性:", self.uname)
        print("调用私有属性:", self.__uage)
        print("调用私有类属性:", self.__price)

使用 dir()函数可以查看对象内的所有的属性和方法,#

在 python 中任何东西都是对象,一种数据类型,一个模块等,都有子集的属性和方法,除了常用的方法外,其他的你不需要全部记住它,交给 dir() 函数就好了。

d = Demo('Tom', 18)
print(dir(d))
"""
['_Demo__age', '_Demo__price', '_Demo__uage', '__class__', '__delattr__', '__dict__', 
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',  '__str__', 
'__subclasshook__', '__weakref__', 'name', 'uname']
"""

这些打印出来的属性(方法)是可以直接调用的。从打印的结果可以看到,私有属性 '__age()'、 '__price'、'__uage' 这三个私有属性(方法)都变成了 '_Demo__age', '_Demo__price', '_Demo__uage',也就可以看出,私有属性(方法)在Python中是不允许直接去调用的,类外部可以通过 ”_类名__私有属性(方法)名“ 访问私有属性(方法)

调用属性(方法)

# 调用共有方法
d.name
"""
这是公有方法
调用共有属性: Tom
调用私有属性: 18
调用私有类属性: 25.8
"""

# 调用私有方法(错误示范)
d.__age()
"""
Traceback (most recent call last):
  File "D:/Local/PycharmProjects/private_obj/demo.py", line 32, in <module>
    d.__age()
AttributeError: 'Demo' object has no attribute '__age'
"""

# 调用私有方法(正确示例)
d._Demo__age()
d._Demo__
"""
这是私有方法
调用共有属性: Tom
调用私有属性: 18
调用私有类属性: 25.8
"""

# 调用私有属性
print(Demo._Demo__price) # 25.8
print(d._Demo__uage) # 18

1、类的公有成员

class A:

    # 公有静态属性
    name = "Jane"

    def __init__(self, username):
        # 公有对象属性
        self.username = username

    # 公有动态方法
    def func(self):
        pass

2. 类的私有成员,就是在普通的属性和方法名前加两个下划线

class A:

    # 公有静态属性
    name = "Jane"
    # 私有静态属性
    __country = "中国"

    def __init__(self, username, password):
        # 公有对象属性
        self.username = username
        # 私有对象属性
        self.__password = password

    # 公有动态方法
    def func(self):
        pass

    # 私有动态方法
    def __func(self):
        pass

3. 私有静态属性只能在类的内部被访问,无论是类名还是实例化对象对其访问

class Boss:

    name = "Jane"
    __secretary = ["女", "男"]

    def __init__(self, username, password):
        self.username = username
        self.__password = password

    def func(self):
        self.__func()

    def __func(self):
        print(self.__secretary)

class Boss_son(Boss):

    def func(self):
        print(self.__secretary)


# 类外部访问类的私有静态属性
print(Boss.__secretary)
# 运行结果:
Traceback (most recent call last):
  File "test01.py", line 23, in <module>
    print(Boss.__secretary)
AttributeError: type object 'Boss' has no attribute '__secretary'

# 类内部的 func() 访问
b = Boss("aaa", 123)
b.func()        # ['女', '男']
b.__secretary   
# 运行结果:
Traceback (most recent call last):
  File "test01.py", line 30, in <module>
    b.__secretary   
AttributeError: 'Boss' object has no attribute '__secretary'


# 通过子类来访问
b1 = Boss_son("bbb", 222)
b1.func()
# 运行结果:
Traceback (most recent call last):
  File "test01.py", line 33, in <module>
    b1.func()
  File "test01.py", line 19, in func
    print(self.__secretary)
AttributeError: 'Boss_son' object has no attribute '_Boss_son__secretary'

 

posted @ 2021-06-18 18:16  fat_girl_spring  阅读(685)  评论(0编辑  收藏  举报