Python 中的依赖类

问题描述 投票:0回答:1

编辑:经过评论中的讨论,这是问题的技术部分。还有审美方面,如何巧妙地做到这一点。

如何创建依赖于参数的类,但相同的参数会产生相同的类?像这样的东西:

def create_class(n):
    class Bar:
        nn = n
    return Bar

a = create_class(3)
b = create_class(3)
print(a==b) #False

在此示例中,生成的类是不同的。有没有办法动态生成相等的类?

编辑前的问题: 我现在的实现是使用大型类,大型类本身创建较小的类作为参数。它在上面的相等性测试中失败了,还有一个丑陋的长类定义。

class Foo:
    def __init__(self, n):
        self.n = n

        class Bar:
            nn = n
            def __init__(self, m):
                print("This uses n={} and m={} in funny ways".format(Bar.nn, m))
        self.B = Bar

        class Barr(Bar):
            nnn = n+1
            def asd(self):
                print("I have inheritance too {} {}".format(Bar.nn, Barr.nnn))
        self.BB = Barr
    
    def __eq__(self, other):
        return type(self)==type(other) and self.n==other.n

然后我按以下方式使用它们:

a = Foo(3) 
b = a.B(10) 
#This uses n=3 and m=10 in funny ways
bb = a.BB(1) 
#This uses n=3 and m=1 in funny ways
bb.asd() 
#I have subclasses too 3 4
aa = Foo(5)
print(b == aa.B(10)) #should be false
#This uses n=5 and m=10 in funny ways
#False

参数一致时也无法匹配类:

ap = Foo(3)
print(ap==a) #True
print(ap.B==a.B) #False

我用 eq 覆盖强制实现的第一个不等式,但生成的 Bar 类似乎总是不同。我知道

type(a, b, c)
类构造函数,但这些类依赖于复杂变量(如果 n 是上面示例中的复杂对象),所以我不能像 Bar1 Bar2 这样对它们进行编号...

有没有一种简洁而优雅的方法来处理像Python中的类这样的依赖类型?

python python-3.x oop python-2.x dependent-type
1个回答
0
投票

一种方法是存储您之前创建的类,只有在没有具有相同参数的类时才创建一个新类。您可以使用

WeakValueDictionary
,这样一旦它们消失在其他地方,您就不会不必要地永久存储它们,如下所示:

import weakref

def create_class(n):
    class Bar:
        nn = n
    return Bar

d = weakref.WeakValueDictionary()
def get_or_create_class(n):
    try:
        return d[n]
    except KeyError:
        c = create_class(n)
        d[n] = c
        return c

a = get_or_create_class(3)
b = get_or_create_class(3)
print(a==b) #True
© www.soinside.com 2019 - 2024. All rights reserved.