可以在班级名称上找到classmethod

发布于 2025-01-20 18:54:19 字数 1249 浏览 1 评论 0原文

我正在尝试通过className .AttributeError问题调用classMethod。

当我使用@singleton时,我无法使用className.functionname .functionname .in className()。functionName。 为什么会发生这种情况?

def singleton(cls):
    '''
    单例
    :param cls:
    :return:
    '''
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
            # print(type(_instance[cls])) <class '__main__.Coco'>
        return _instance[cls]

    return _singleton


@singleton
class Coco():

    # def __new__(cls, *args, **kwargs):
    #     if not hasattr(Coco, "_instance"):
    #         if not hasattr(Coco, "_instance"):
    #             Coco._instance = object.__new__(cls)
    #             print(type(Coco._instance))
    #     return Coco._instance

    def __init__(self):
        print('coco')

    @classmethod
    def get_info(cls):
        print('coco is 18 ages old')

# print(Coco().get_info())
print(Coco.get_info())

例外

Traceback (most recent call last):
  File "/Users/coco/Automation/AutoTestRes/scripts/python/coco.py", line 36, in <module>
    print(Coco.get_info())
AttributeError: 'function' object has no attribute 'get_info'

I am trying to invoke classmethod over classname .AttributeError problem occurs

When I use @singleton ,I can't run with classname.functionname .It's must be classname().functionname
Why does this happen?

def singleton(cls):
    '''
    单例
    :param cls:
    :return:
    '''
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
            # print(type(_instance[cls])) <class '__main__.Coco'>
        return _instance[cls]

    return _singleton


@singleton
class Coco():

    # def __new__(cls, *args, **kwargs):
    #     if not hasattr(Coco, "_instance"):
    #         if not hasattr(Coco, "_instance"):
    #             Coco._instance = object.__new__(cls)
    #             print(type(Coco._instance))
    #     return Coco._instance

    def __init__(self):
        print('coco')

    @classmethod
    def get_info(cls):
        print('coco is 18 ages old')

# print(Coco().get_info())
print(Coco.get_info())

Exception

Traceback (most recent call last):
  File "/Users/coco/Automation/AutoTestRes/scripts/python/coco.py", line 36, in <module>
    print(Coco.get_info())
AttributeError: 'function' object has no attribute 'get_info'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光下慵懒的猫 2025-01-27 18:54:19

当您在Python中使用装饰器时,如下:

@decorator_name
class class_name:
    ...

...,这相当于这样做:

class class_name:
    ...
class_name = decorator_name(class_name)

这意味着变量class_name不再是一类,而是什么,而是任何内容decorator_name的返回值是。

在您的情况下,类Decorator Singleton返回函数 _Singleton,而不是实际类。因此,当您说:

print(Coco.get_info())

相同

print(_singleton.get_info())

...,这与说: ...在功能中

。因此,您将获得attributeError,因为该函数现在具有名称coco,它没有该属性。

要访问类的属性,您需要运行该功能,因为这将返回类的实例,该实例将具有属性。

不再有可能从全局范围访问课程本身。

When you use a decorator in Python, like this:

@decorator_name
class class_name:
    ...

..., this is equivalent to doing this:

class class_name:
    ...
class_name = decorator_name(class_name)

This means that the value of the variable class_name is no longer necessarily a class, but instead it is whatever the return value of decorator_name is.

In your case, the class decorator singleton returns the function _singleton, not the actual class. So when you say:

print(Coco.get_info())

..., this is the same as saying:

print(_singleton.get_info())

...within the function.

Therefore, you get an AttributeError, because the function, which now has the name Coco, does not have that attribute.

To access the attribute of the class, you need to run the function because this will return an instance of the class, which will have the attribute.

It is no longer possible to access the class itself from the global scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文