首页 > 其他分享 >classonlymethod和classmethod区别

classonlymethod和classmethod区别

时间:2022-11-06 21:04:23浏览次数:29  
标签:__ classonlymethod 区别 classmethod None print view cls

如果要使用classonlymethod ,则需要先定义好一个classonlymethod 类。

首先我们需要明白无论是classonlymethod还是classmethod,本质都是一个类,而classonlymethod继承了classmethod。
classonlymethodz作用:只能被类调用,不能被实例对象调用。

class classonlymethod(classmethod):  # 继承classmethod
    def __get__(self, instance, cls=None): # 
        if instance is not None:
            raise AttributeError("This method is available only on the class, not on instances.")
        return super(classonlymethod, self).__get__(instance, cls)

示例2

from django.utils.decorators import classonlymethod


class Foo:
    def __init__(self, name, a = None):
        self.name = name

    @classonlymethod
    def as_view(cls, actions=None, **initkwargs):
        """
        Because of the way class based views create a closure around the
        instantiated view, we need to totally reimplement `.as_view`,
        and slightly modify the view function that is created and returned.
        """
        # The name and description initkwargs may be explicitly overridden for
        # certain route confiugurations. eg, names of extra actions.
        cls.name = None
        cls.description = None
        page = None

        # The suffix initkwarg is reserved for displaying the viewset type.
        # This initkwarg should have no effect if the name is provided.
        # eg. 'List' or 'Instance'.
        cls.suffix = None

        # The detail initkwarg is reserved for introspecting the viewset type.
        cls.detail = None

        # Setting a basename allows a view to reverse its action urls. This
        # value is provided by the router through the initkwargs.
        cls.basename = None

        # actions must not be empty
        if not actions:
            raise TypeError("The `actions` argument must be provided when "
                            "calling `.as_view()` on a ViewSet. For example "
                            "`.as_view({'get': 'list'})`")


    def tell(self):    #  绑定到对象
        print('名字是%s'%self.name)

    @classonlymethod
    def tell2(cls, page=None):    #  绑定到对象
        print('@classonlymethod名字是%s'%cls.tell)
        if page is not None:
            print(page,'page你好啊')

    @classmethod   #  绑定到类
    def func(cls):
        print(cls,'这是classmethod')

    @staticmethod    #  非绑定方法,静态方法
    def func1(x,y):
        print(x+y)


f = Foo('egon')
print(f,'对象f')

def func3():print('这是函数func3')
print(Foo.func,'函数func')
Foo.func()
print('-----------1-----------')
Foo.tell2()
print(Foo.tell2.__module__)
Foo.tell2(123)
print('---------2-------------')
# f.tell2()
Foo.as_view(actions='get')
f.as_view(actions='get')     #
print(Foo.as_view.__module__)

输出:

Traceback (most recent call last):
  File "D:/python3.64/sss/python_note/面向对象/21_绑定方法与非绑定方法介绍.py", line 72, in <module>
    f.as_view(actions='get')     #
  File "D:\PythonVenv\drf_venv\lib\site-packages\django\utils\decorators.py", line 11, in __get__
    raise AttributeError("This method is available only on the class, not on instances.")
AttributeError: This method is available only on the class, not on instances.
<__main__.Foo object at 0x00000228236ED3C8> 对象f
<bound method Foo.func of <class '__main__.Foo'>> 函数func
<class '__main__.Foo'> 这是classmethod
-----------1-----------
@classonlymethod名字是<function Foo.tell at 0x000002282392C8C8>
__main__
@classonlymethod名字是<function Foo.tell at 0x000002282392C8C8>
123 page你好啊
---------2-------------

标签:__,classonlymethod,区别,classmethod,None,print,view,cls
From: https://www.cnblogs.com/heris/p/16863893.html

相关文章

  • 谈谈过滤器和拦截器的区别
    一、拦截器和过滤器的区别1、拦截器(Interceptor)只对action请求起作用即对外访问路径而过滤器(Filter)则可以对几乎所有的请求都能起作用包括cssjs等资源文件2、拦......
  • 野花--css实现元素竖向排列 --- writing-mode和flex的区别
    第一种:使用flex方法前提条件1.父元素有宽度和高度.box{background-color:#9bceea;height:60px;width:90px;display:flex;flex-direction:column;......
  • 线程和进程,并发和并行的区别
    线程和进程计算机教材上的经典定义如下:线程是操作系统调度的基本单位;进程是操作系统资源分配的基本单位。线程和进程属于一个抽象的概念,具体实现还得看具体的操作系统......
  • JSON字符串与JSON对象的区别
    Q:什么是"JSON字符串",什么是"JSON对象",两者的区别?a.JSON对象是直接可以使用JQuery操作的格式,如js中可以用对象(类名)点出属性(方法)一样b.JSON字符串仅仅只是一个字符串,一个......
  • maven中dependencyManagement与dependencies的区别与联系
    背景新的需求中需要使用到easyexcel中的动态生成列的功能,但是因为我们项目一开始使用的是1.2.4-beta的低版本,并不支持此项特性,所以我们需要将easyexcel的版本升级到高版本......
  • 进程与线程的区别
    一、进程一个在内存中运行的应用程序。每个进程都有自己独立的一块内存空间,一个进程可以有多个线程,在Windows系统中,每个运行的应用程序就是一个进程。二、线程进程中的......
  • cookie和session的区别
    1.什么是cookie?Http协议本身是无状态的,即服务器无法判断用户身份。Cookie实际上是一小段文本信息,客户端向服务器发起请求,如果服务器需要记录该用户状态,就使用response......
  • merge及其与sql的区别
    merge语句用merge语句将两个或多个SAS数据集中的观测值横向匹配合并成一个新的数据集的一个观测值。DATA<新数据集名称>;MERGE<已有数据集列表>;BY<变量1>[<变量2>…......
  • attr与prop的区别
    与prop一样attr也可以用来获取与设置元素的属性。区别在于,对于自定义属性和选中属性的处理。选中属性指的是checked,selected这2种属性1.对于自定义属性attr能够获......
  • Hive Order By,Sort by,Distribute By,Cluster By 排序区别
    OrderByOrderBy:全局排序,只有一个Reducer,就算提前设置好n个reducerorderby也是只执行一个reducer,因为全局排序,排序的仅仅是一个表罢了。orderby对于大规模数据集......