zoukankan      html  css  js  c++  java
  • @staticmethod和@classmethod的用法

    classonlymethodz作用:只能被类调用,不能被实例对象调用。

    class A(object):
        bar = 1
        def foo(self):
            print( 'foo')
    
        @staticmethod
        def static_foo():
            print( 'static_foo')
            print (A.bar)
    
        @classmethod
        def class_foo(cls):
            print ('class_foo')
            print (cls.bar)
            cls().foo()
    A.static_foo()
    A.class_foo()
    

    面向对象中的@classonlymethod 与 @classmethod的区别
    如果要使用classonlymethod ,则需要先定义好一个classonlymethod 类。
    首先我们需要明白无论是classonlymethod还是classmethod,本质都是一个类,而classonlymethod继承了classmethod。

    class classonlymethod(classmethod):
        def __get__(self, instance, owner):
            if instance is not None:
                raise AttributeError('This method is available only on the view class .')
            return super(classonlymethod, self).__get__(instance, owner)
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    MySQL索引底层数据结构
    numpy和matplotlib读书笔记
    Python turtle学习笔记 #11933
    turtle笔记
    五角星绘制
    六角形绘制
    叠加等边三角形绘制
    什么叫方法签名
    Java编程思想 第七章
    类加载机制
  • 原文地址:https://www.cnblogs.com/heris/p/14667921.html
Copyright © 2011-2022 走看看