gpt4 book ai didi

python - 在类变量中引用类方法

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

如何在类变量中引用类方法?

例如:

我有

class UU(object):

map = {
'username': get_username
}

@classmethod
def get_username(cls):
pass

但是,找不到get_username

我尝试了 UU.get_username 但似乎没有用。

最佳答案

类体像函数一样被执行,然后局部命名空间变成类属性。

因此适用正常的命名顺序要求;您不能引用 get_username(),因为它尚未定义

此外,即使您将 map 定义移到 get_username() 下方,您也会得到未绑定(bind)的 classmethod 对象 定义。

因此,您可以在创建类后将方法添加到映射中:

class UU(object):
@classmethod
def get_username(cls):
pass

UU.map = {
'username': UU.get_username
}

请注意,这意味着 UU.map['username'] 正在使用绑定(bind)到 UU 类的 classmethod .如果您曾经对 UU 进行子类化并提供了该方法的重写,您将不会在子类上获得该版本。

您必须跳过更多的环节才能使它适用于子类;你必须让 map 成为 descriptor object所以你可以在映射中查找值时绑定(bind)类方法,而不是在定义映射时:

class BindingMap(dict):
def __get__(self, instance, cls=None):
return {k: v.__get__(instance, cls) if hasattr(v, '__get__') else v for k, v in self.items()}

class UU(object):
@classmethod
def get_username(cls):
pass

map = BindingMap({
'username': get_username,
})

映射将根据需要生成绑定(bind)的类方法,扩展到子类:

>>> class BindingMap(dict):
... def __get__(self, instance, cls=None):
... return {k: v.__get__(instance, cls) if hasattr(v, '__get__') else v for k, v in self.items()}
...
>>> class UU(object):
... @classmethod
... def get_username(cls):
... pass
... map = BindingMap({
... 'username': get_username,
... })
...
>>> UU.map
{'username': <bound method type.get_username of <class '__main__.UU'>>}
>>> UU.map['username']
<bound method type.get_username of <class '__main__.UU'>>
>>> UU.map['username']()
>>> class UU(object):
... @classmethod
... def get_username(cls):
... print('Username for class {}'.format(cls.__name__))
... map = BindingMap({
... 'username': get_username,
... })
...
>>> UU.map
{'username': <bound method type.get_username of <class '__main__.UU'>>}
>>> UU.map['username']
<bound method type.get_username of <class '__main__.UU'>>
>>> UU.map['username']()
Username for class UU
>>> class Foo(UU):
... pass
...
>>> Foo.map
{'username': <bound method type.get_username of <class '__main__.Foo'>>}
>>> Foo.map['username']
<bound method type.get_username of <class '__main__.Foo'>>
>>> Foo.map['username']()
Username for class Foo

关于python - 在类变量中引用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29266828/

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