• 两个装饰器

    • classmethod : 被装饰的方法会成为一个静态方法

      • classmethod 什么时候用?

        1. 定义了一个方法,默认传self,但是这个self没有被用到
        2. 并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候
      • 定义:

        • 装饰器怎么加

        • 参数怎么改

          class Goodds:__dicount = 0.8def __init__(self):self.__Price = 5self.price = self.__Price * self.__dicount@classmethoddef change_discount(cls, new_discount):cls.__dicount = new_discount
      • 用法:

        • 调用方法

          class Goodds:__dicount = 0.8def __init__(self):self.__Price = 5self.price = self.__Price * self.__dicount@classmethoddef change_discount(cls, new_discount):cls.__dicount = new_discount
          # 类方法可以通过类名调用
          Goodds.change_discount(0.6)
          apple = Goodds()
          print(apple.price)
          # 类方法可以通过对象名调用
          apple.change_discount(0.5)
          apple2 = Goodds()
          print(apple2.price)# import time
          # class Date:
          #     def __init__(self, year, month, day):
          #         self.year = year
          #         self.month = month
          #         self.day = day
          #
          #     @classmethod
          #     def today(cls):
          #         struct_t = time.localtime()
          #         date = cls(struct_t.tm_year, struct_t.tm_mon, struct_t.tm_mday)
          #         return date
          #
          #
          # date_obj = Date.today()
          # print(date_obj.year)
          # print(date_obj.month)
          # print(date_obj.day)
          # # 2019
          # # 6
          # # 5
          
      • staticmethod : 被装饰的方法会成为一个静态方法

        • 用在:

          帮助我们把一个普通的函数挪到类中来直接使用,制造静态方法用的

        • 定义:

          class User:
          #     @staticmethod
          #     def login(a, b):
          #         print("登陆逻辑", a, b)
          #         # 在函数的内部既不会用到self变量,也不会用到cls类
          # 本身是一个普通的函数,被挪到类的内部执行,那么直接给这个函数添加@staticmethod装饰器就可以了
        • 调用方法:

          # class User:
          #     @staticmethod
          #     def login(a, b):
          #         print("登陆逻辑", a, b)
          #         # 在函数的内部既不会用到self变量,也不会用到cls类
          #
          # obj = User()
          # User.login(1, 2)
          # obj.login(3, 4)
          class A:country = '中国'def func(self):print(self.__dict__)@classmethoddef clas_func(cls):print(cls)@staticmethoddef stat_func():print("普通函数")@propertydef name(self):return 'wahah'# 能定义到类中的内容
          # 静态变量 是个所有的对象共享的变量  有对象\类调用 但是不能重新赋值
          # 绑定方法 是个自带self参数的函数    由对象调用
          # 类方法   是个自带cls参数的函数     由对象\类调用
          # 静态方法 是个啥都不带的普通函数    由对象\类调用
          # property属性 是个伪装成属性的方法  由对象调用 但不加括号
  • 一些内置的魔术方法

    • ___new___
      class A:def __new__(cls, *args, **kwargs):o = object.__new__(cls)print("执行new", o)return odef __init__(self):print('执行initt', self)A()
      # 执行new <__main__.A object at 0x0000002F1E569048>
      # 执行initt <__main__.A object at 0x0000002F1E569048># 实例化的时候,
      # 先创建一块对象的空间,有个指针能指向类 --》 __new__
      # 调用init--> __init__# 设计模式 -- 单例模式
      # 一个类,从头到尾只会创建一次self的空间class Baby:__instance = Nonedef __new__(cls, *args, **kwargs):if cls.__instance is None:# cls.__instance = super().__new__(cls)cls.__instance = object.__new__(cls)return cls.__instancedef __init__(self, cloth, pants):self.cloth = clothself.pants = pantsb1 = Baby('红毛衣', '绿裤子')
      print(b1.cloth)
      b2 = Baby('白衬衫', '黑裤子')
      print(b1.cloth)
      print(b2.cloth)# 单例模式2.0:
      class Baby:def __init__(self, cloth, pants):self.cloth = clothself.pants = pants
      b1 = Baby('红上衣', '绿裤子')
      # 通过模块引用的方式
      # from 单例模式 import b1
      # from 单例模式 import b1
      
    • __cal__
      """ Call self as a function. """
      # class A:
      #     pass
      #
      # obj = A()
      # print(callable(obj))
      # Falseclass A:def __call__(self, *args, **kwargs):print('___', args)
      obj = A()
      print(callable(obj))
      obj()
      # True
      # ___ ()
    • __len__class Cls:def __init__(self, name):self.name = nameself.student = []def len(self):return len(self.student)def __len__(self):return len(self.student)py22 = Cls('py22')
      py22.student.append('abc')
      py22.student.append('123')
      py22.student.append('qaz')
      print(len(py22))class Pow:def __init__(self, n):self.n = ndef __pow2__(self):return self.n ** 2def pow2(obj):return obj.__pow2__()obj = Pow(10)
      print(pow2(obj))
    • __str__
      class Course:
      #     def __init__(self, name, price, period):
      #         self.name = name
      #         self.price = price
      #         self.period = period
      #
      #     def __str__(self):
      #         return self.name
      #
      # python = Course('python', 21800, '6 month')
      # linux = Course('linux', 19800, '5 month')
      # mysql = Course('mysql', 12800, '3 month')
      # go = Course('go', 15800, '4 month')
      # print(go)
      # # goclass cls:def __init__(self):self.student = []def append(self, name):self.student.append(name)def __str__(self):return str(self.student)
      py22= cls()
      py22.append('大壮')
      print("我们py22班 %s" %py22)
      print(py22)
      py22.append('小状')
      print(py22)
      # 在打印一个对象的时候 调用__str__方法
      # 在%s拼接一个对象的时候 调用__str__方法
      # 在str一个对象的时候 调用__str__方法
    • __repr__
      py22 = clas()
      py22.append('大壮')
      print(py22)
      print(str(py22))
      print('我们py22班 %s'%py22)
      print('我们py22班 %r'%py22)
      print(repr(py22))
      # 当我们打印一个对象 用%s进行字符串拼接 或者str(对象)总是调用这个对象的__str__方法
      # 如果找不到__str__,就调用__repr__方法
      # __repr__不仅是__str__的替代品,还有自己的功能
      # 用%r进行字符串拼接 或者用repr(对象)的时候总是调用这个对象的__repr__方法
      

转载于:https://www.cnblogs.com/zh-lei/p/10995191.html

classmethod和staticmethod相关推荐

  1. python classmethod知识_python基础知识讲解——@classmethod和@staticmethod的作用

    python基础知识讲解--@classmethod和@staticmethod的作用 在类的成员函数中,可以添加@classmethod和@staticmethod修饰符,这两者有一定的差异,简单来 ...

  2. @classmethod和@staticmethod对初学者的意义? [重复]

    本文翻译自:Meaning of @classmethod and @staticmethod for beginner? [duplicate] This question already has ...

  3. python知识:@classmethod和@staticmethod的异同

    1 说明 @staticmethod的意思就是将后面的函数转化成静态函数. 大多数情况,@classmethod和@staticmethod效果一样.但是那不是正题,正式作用是类工厂,如果有类继承关系 ...

  4. python @classmethod 和 @staticmethod区别,以及类中方法参数cls和self的区别

    一.@classmethod 和 @staticmethod 1.staticmethod 作用:让类中的方法变成一个普通函数(普通函数没有绑定在任何一个特定的类或者实例上.所以与不需要对象实例化就可 ...

  5. python的@classmethod和@staticmethod

    本文是对StackOverflow上的一篇高赞回答的不完全翻译,原文链接:meaning-of-classmethod-and-staticmethod-for-beginner Python面向对象 ...

  6. python中classmethod与staticmethod的差异及应用

    类中三种函数的应用 #!/usr/bin/env python # -*- coding: utf-8 -*-class TClassStatic(object):def __init__(self, ...

  7. [转载] python staticmethod有什么意义_Python 中的 classmethod 和 staticmethod 有什么具体用途

    参考链接: Python staticmethod() >>> type(a1) example 2: class a(object): @classmethod def cm(cl ...

  8. [转载] python classmethod存在的意义_@classmethod和@staticmethod对初学者的意义?

    参考链接: Python classmethod() 尽管classmethod和staticmethod非常相似,但这两个实体的用法略有不同:classmethod必须将对类对象的引用作为第一个参数 ...

  9. Python中classmethod与staticmethod区别

    classmethod:类方法 staticmethod:静态方法 在python中,静态方法和类方法都是可以通过类对象和类对象实例访问.但是区别是: @classmethod 是一个函数修饰符,它表 ...

最新文章

  1. iOS RunLoop详解
  2. 8款帅酷的HTML5/CSS3 3D动画、图片、菜单应用
  3. 衡量计算机的平均无故障时间6,平均无故障时间MTBF测试及计算过程
  4. 【译】SQL Server误区30日谈-Day8-有关对索引进行在线操作的误区
  5. 从零开始配置MySQL MMM
  6. MySQL Explain详解,分析语句为何运行慢
  7. C++:从C继承的标准库
  8. HTML+CSS+JS实现 ❤️等离子球体ui动画特效❤️
  9. 分屏总屏计算机电缆,分屏加总屏电缆DJYVP计算机电缆14x2x0.75
  10. 【HDOJ6986】Kanade Loves Maze Designing(暴力,dfs树)
  11. Flutter进阶第8篇:实现视频播放
  12. html表头和左侧固定js,固定表头jquery datatable的使用与定制
  13. matlab安装后不能打开怎么办,matlab7.0安装后打不开_matlab7.0安装后不能用
  14. java中钟摆运动的代码_仿真树叶飘落效果的实现(精灵旋转、翻转、钟摆运动等综合运用)...
  15. 移动电视一直显示Android,移动机顶盒恢复出厂设置后显示android正在升级?
  16. 《你见,或者不见我》
  17. 小年到了,用 Python 实现一场环保无污染的烟花秀,祝大家节日快乐
  18. 飞机机翼的构造及其原理
  19. Ewebeditor的问题
  20. Android R config_biometric_sensors默认通用定制common可好?

热门文章

  1. 从0到1演示用 Git Rerere 自动解决冲突
  2. 【洛谷3648】[APIO2014] 序列分割(斜率优化DP)
  3. 练习题 James and Dominoes
  4. filter---用angularjs实现关键字高亮
  5. Programming Pearls Essay 01
  6. php 清除缓存的操作,PHP清除缓存的几种方法
  7. java文件的相对路径_java中使用相对路径读取文件的写法总结 ,以及getResourceAsStream() (转)...
  8. Ubuntu 下Mysql常用命令
  9. 北工大计算机学院教授,北工大计算机学院计算机科学与技术导师介绍:周艺华...
  10. python web自动化_Selenium+Python Web自动化