python如何添加属性_如何添加元类属性?

我想定义元类,使我能够在新类的属性基础上创建属性(即setter、getter)。在

例如,我想定义类:class Person(metaclass=MetaReadOnly):

name = "Ketty"

age = 22

def __str__(self):

return ("Name: " + str(self.name) + "; age: "

+ str(self.age))

但我想要这样的东西:

^{pr2}$

下面是我写的元类:class MetaReadOnly(type):

def __new__(cls, clsname, bases, dct):

result_dct = {}

for key, value in dct.items():

if not key.startswith("__"):

result_dct["__" + key] = value

fget = lambda self: getattr(self, "__%s" % key)

fset = lambda self, value: setattr(self, "__"

+ key, value)

result_dct[key] = property(fget, fset)

else:

result_dct[key] = value

inst = super(MetaReadOnly, cls).__new__(cls, clsname,

bases, result_dct)

return inst

def raiseerror(self, attribute):

raise RuntimeError("%s is read only." % attribute)

但是它不能正常工作。在client = Person()

print(client)

有时我得到:

Name: Ketty; age: Ketty

有时:

Name: 22; age: 22

甚至是一个错误:Traceback (most recent call last):

File "F:\Projects\TestP\src\main.py", line 38, in

print(client)

File "F:\Projects\TestP\src\main.py", line 34, in __str__

return ("Name: " + str(self.name) + "; age: " + str(self.age))

File "F:\Projects\TestP\src\main.py", line 13, in

fget = lambda self: getattr(self, "__%s" % key)

AttributeError: 'Person' object has no attribute '____qualname__'

我已经找到了一个例子,可以用其他方法来实现Python classes: Dynamic properties,但我想用元类来做。你知道如何做到这一点吗?或者说这是可能的吗?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值