如何使用Python的__set__、__get__和__delete__魔法方法实现属性封装?

2026-05-24 13:372阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计145个文字,预计阅读时间需要1分钟。

如何使用Python的__set__、__get__和__delete__魔法方法实现属性封装?

pythonclass Attr(object): def __init__(self, attrname, attrtype): self.attrname=attrname self.attrtype=attrtype

def __get__(self, instance, owner): return instance.__dict__[self.attrname]

def __set__(self, instance, value): if not isinstance(value, self.attrtype): raise TypeError(Value must be of type + str(self.attrtype))

class Attr(object):
def __init__(self,attrname,attrtype):
self.attrname=attrname
self.attrtype=attrtype
def __get__(self,instance,value):
return instance.__dict__[self.attrname]
def __set__(self,instance,value):
if not isinstance(value,self.attrtype):
raise TypeError("%s type error"%self.attrname)
instance.__dict__[self.attrname]=value
def __delete__(self,instance):
del instance.__dict__[self.attrname]

class Person(object):
name=Attr("name",str)
age=Attr("age",int)
p=Person()
p.age="23"

如何使用Python的__set__、__get__和__delete__魔法方法实现属性封装?


本文共计145个文字,预计阅读时间需要1分钟。

如何使用Python的__set__、__get__和__delete__魔法方法实现属性封装?

pythonclass Attr(object): def __init__(self, attrname, attrtype): self.attrname=attrname self.attrtype=attrtype

def __get__(self, instance, owner): return instance.__dict__[self.attrname]

def __set__(self, instance, value): if not isinstance(value, self.attrtype): raise TypeError(Value must be of type + str(self.attrtype))

class Attr(object):
def __init__(self,attrname,attrtype):
self.attrname=attrname
self.attrtype=attrtype
def __get__(self,instance,value):
return instance.__dict__[self.attrname]
def __set__(self,instance,value):
if not isinstance(value,self.attrtype):
raise TypeError("%s type error"%self.attrname)
instance.__dict__[self.attrname]=value
def __delete__(self,instance):
del instance.__dict__[self.attrname]

class Person(object):
name=Attr("name",str)
age=Attr("age",int)
p=Person()
p.age="23"

如何使用Python的__set__、__get__和__delete__魔法方法实现属性封装?