gpt4 book ai didi

python - 如何使每个类的类属性分开以避免被不同类覆盖?

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

简单示例 Parent 是具有 version 属性的类。我想从此类继承,但避免在所有继承类之间共享版本属性。

class Parent(object):
versions = []

@classmethod
def add_version(cls, version):
cls.versions.append(version)

class P1(Parent):
pass

class P2(Parent):
pass

class Thing(object):
pass

P1.add_version(Thing)
# should be Thing
print(P1.versions)
# should be empty [] by my design but it works other way in Python
# how to achieve to different versions fields without coding it in child classes?
print(P2.versions)

由于类之间共享版本而产生这样的结果 - 如何避免?

[<class '__main__.Thing'>]
[<class '__main__.Thing'>]

最佳答案

从技术上讲,您不需要一个元类——一个简单的类装饰器也可以工作(好吧,有点……):

def versions_container(cls):
if "versions" not in cls.__dict__:
print("adding versions to class {}".format(cls.__name__))
cls.versions = []
return cls


@versions_container # this one is useless but anyway...
class Parent(object):
versions = []
@classmethod
def add_version(cls, version):
cls.versions.append(version)

@versions_container
class P1(Parent):
pass

@versions_container
class P2(Parent):
pass

class Thing(object):
pass

P1.add_version(Thing)
print(P1.versions)
print(P2.versions)

但是这并不比在每个子类中手动添加versions 属性好多少。

自定义元类解决方案并不是什么大问题,它可以确保您的代码的用户不会违反预期:

class VersionsContainer(type):
def __new__(meta, name, bases, attrs):
if "versions" not in attrs:
attrs["versions"] = []
return type.__new__(meta, name, bases, attrs)

class Parent(object, metaclass=VersionContainer):
@classmethod
def add_version(cls, version):
cls.versions.append(version)

class P1(Parent):
pass

class P2(Parent):
pass

class Thing(object):
pass

P1.add_version(Thing)
print(P1.versions)
print(P2.versions)

关于python - 如何使每个类的类属性分开以避免被不同类覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302844/

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