|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2023/2/14 21:47
# @Author : xiongming
# @File : shiyoubianlaing.py
# @Desc : 私有变量-name_mangling
class C:
def __init__(self, x):
self.__x = x
def set_x(self, x):
self.__x = x
def get_x(self):
print(self.__x)
c = C(250)
# c.__x 报错
c.get_x()
c.set_x(520)
c.get_x()
print(c.__dict__)
print(c._C__x)
class D():
def __func(self):
print("Hello")
d = D()
# d.__func() 报错
d._D__func()
# 动态添加私有属性
c.__y = 100
print(c.__dict__)
# _单个下横线开头的变量,内部变量,不易访问
# 单个下横线结尾的变量
class D():
# 限制了属性,不能添加额外的,划出固定空间给属性
# 继承自父类的__slots__属性是不会在子类中生效的
__slots__ = ["x", "y"]
def __init__(self, x):
self.x = x
d = D(5)
print(d.x)
d.y = 11
print(d.y)
# d.z = 66 报错
# 继承自父类的__slots__属性是不会在子类中生效的
class E(D):
pass
e = E(33)
print(e.x)
e.y = 55
print(e.y)
e.z = 22
print(e.__slots__)
print(e.__dict__) |
|