gpt4 book ai didi

python - 属性创建函数

转载 作者:太空宇宙 更新时间:2023-11-04 09:41:18 25 4
gpt4 key购买 nike

我想在一个对象中有一个函数来创建某个行为的成员。类似于使用 @property 装饰器。但不必声明 getter 和 setter 函数。我想使用相同的 getter 和 setter 函数创建自定义行为的许多成员。但是这个例子不起作用。当我运行它时,new_prop 成员是一个属性对象,而不是成员。我怎样才能实现我的目标?

class MyClass():
def __init__(self):
self.new_prop("my_prop1")
self.new_prop("my_prop2")
self.new_prop("my_prop3")

def new_prop(self, name):
def getter(self):
this_prop = getattr(self, "_" + name)
if this_prop is None:
return "This is None!"
else:
return this_prop
def setter(self, value):
setattr(self, "_" + name, value)
setattr(self, name, property(getter, setter))
setattr(self, "_" + name, None)

if __name__ == "__main__":
my_class = MyClass()

print(type(my_class.my_prop1))

最佳答案

property 是一个描述符,与所有描述符一样,它仅在解析为类属性时才被调用 - 正如您所发现的,当它是一个实例属性时,它是 __get__ 并且__set__ 方法未被调用。

如果您的目的只是为了避免为 N 个属性重写相同的 getter 和 setter,那么简单的解决方案就是编写您自己的描述符:

class MyProp(object):
def __init__(self, name):
self.name = name

def __get__(self, obj, cls):
if obj is None:
return self
value = getattr(obj, "_" + self.name)
if value is None:
return "This is None!"
else:
return value

def __set__(self, obj, value):
setattr(obj, "_" + self.name, value)


class Foo(object):
prop1 = MyProp("prop1")
prop2 = MyProp("prop2")

关于python - 属性创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51593062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com