|  | 
 
| 
# !/usr/bin/python3
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  # -*- coding: utf-8 -*-
 # @Time   : 2023/2/19 21:35
 # @Author : xiongming
 # @File   : shuxingxiangguanhanshu.py
 # @Desc   : 属性访问
 
 class C:
 def __init__(self, name, age):
 self.name = name
 self.__age = age
 
 c = C("小甲鱼", 18)
 
 # 查询类的属性是否有name
 a = hasattr(c, "name")
 print(a)
 
 # 获取对象某个属性值
 b = getattr(c, "name")
 
 # name mangling _类名__私有属性名
 e = getattr(c, "_C__age")
 
 print(b)
 print(e)
 
 # setattr 修改私有属性
 setattr(c, "_C__age", 19)
 print(getattr(c, "_C__age"))
 
 # delattr 删除私有属性
 delattr(c, "_C__age")
 print(hasattr(c, "_C__age"))
 
 # 魔法方法
 
 class A:
 def __init__(self, name, age):
 self.name = name
 self.__age = age
 def __getattribute__(self, attrname):
 print("拦截'小甲鱼',拿来吧你")
 return super().__getattribute__(attrname)
 
 
 a = A("小甲鱼", 18)
 aa = getattr(a, "_A__age")
 print(aa)
 a._A__age
 
 class B:
 def __init__(self, name, age):
 self.name = name
 self.__age = age
 def __getattribute__(self, attrname):
 print("拦截'小甲鱼',拿来吧你")
 return super().__getattribute__(attrname)
 def __getattr__(self, item):
 if item == "FishC":
 print("I love FishC")
 else:
 raise AttributeError(item)
 
 print("------BBBB--------")
 bb = B("小甲鱼", 18)
 bb.FishC
 print("------BBBB--------")
 # bb.xx  AttributeError: xx
 
 # setattr
 class DD():
 def __setattr__(self, name, value):
 self.__dict__[name] = value
 def __delattr__(self, name):
 del self.__dict__[name]
 
 dd = DD()
 dd.name = "小甲鱼"
 print(dd.name)
 print(dd.__dict__)
 del dd.name
 print(dd.__dict__)
 
 | 
 |