zoukankan      html  css  js  c++  java
  • Python进阶-----静态方法@property,@classmethod,@staticmethod【转】

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    class cal:
        cal_name = '计算器'
        def __init__(self,x,y):
            self.x = x
            self.y = y
    
        @property           #在cal_add函数前加上@property,使得该函数可直接调用,封装起来
        def cal_add(self):
            return self.x + self.y
    
        @classmethod        #在cal_info函数前加上@classmethon,则该函数变为类方法,该函数只能访问到类的数据属性,不能获取实例的数据属性
        def cal_info(cls):  #python自动传入位置参数cls就是类本身
            print('这是一个%s'%cls.cal_name)   #cls.cal_name调用类自己的数据属性
    
        @staticmethod       #静态方法 类或实例均可调用
        def cal_test(a,b,c): #改静态方法函数里不传入self 或 cls
            print(a,b,c)
    
    
    c1 = cal(10,11)
    cal.cal_test(1,2,3)     #>>> 1 2 3
    c1.cal_test(1,2,3)      #>>> 1 2 3
    cal.cal_info()          #>>> "这是一个计算器"

    输出结果:

    E:PythonPython38python.exe G:/python/爬虫/autoreg/test.py
    1 2 3
    1 2 3
    这是一个计算器

    转自

    Python进阶-----静态方法(@staticmethod) - Meanwey - 博客园
    https://www.cnblogs.com/Meanwey/p/9788713.html

  • 相关阅读:
    git分支
    git使用
    多人协作
    python初心记录二
    python初心记录一
    Javascript 概念类知识
    想成为前端工程师?希望读完这篇文章能对你有所帮助。
    Egret note
    cocos2d-js 连连看
    PS置入图片之后保留选区方便C图
  • 原文地址:https://www.cnblogs.com/paul8339/p/13673506.html
Copyright © 2011-2022 走看看