BrightXiong 发表于 2023-2-19 22:04:30

属性访问_魔法方法

# !/usr/bin/python3
# -*- 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.xxAttributeError: xx

# setattr
class DD():
    def __setattr__(self, name, value):
      self.__dict__ = value
    def __delattr__(self, name):
      del self.__dict__

dd = DD()
dd.name = "小甲鱼"
print(dd.name)
print(dd.__dict__)
del dd.name
print(dd.__dict__)
页: [1]
查看完整版本: 属性访问_魔法方法