zoukankan      html  css  js  c++  java
  • 面向对象编程(三)

    @classmethod 

    @classmethod   # 把一个对象绑定的方法 修改成一个 类方法
    class Course:
        __discount = 0.8
        def __init__(self,name,price,priod):
            self.name = name
            self.price = price
            self.priod = priod
        @classmethod
        def func(cls,new_discount):
            cls.__discount = new_discount
            print(cls.__discount)
    
    Course.func(0.6)    # 0.6
    注意:
    # 第一,在方法中仍然可以引用类中的静态变量
    # 第二,可以不用实例化对象,就直接用类名在外部调用这个方法


    使用场景:

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

    @ staticmethod

    # staticmethod就是把一个普通函数放到类里面进行封装的时候用到的装饰器

    class User:
        def __init__(self,name):
            self.name = name
        @staticmethod
        def func():
            print('我就是一个普通函数')
    User.func()
    u = User('alex')
    u.func()


    总结

    class A:
        country = '中国'
        def func(self):
            print(self.__dict__)
        @classmethod
        def clas_func(cls):
            print(cls)
        @staticmethod
        def stat_func():
            print('普通函数')
        @property
        def name(self):
            return 'wahaha'

    # 能定义到类中的内容
    # 静态变量 是个所有的对象共享的变量   由对象类调用 但是不能重新赋值
    # 绑定方法 是个自带self参数的函数       由对象调用
    # 类方法   是个自带cls参数的函数         由对象类调用
    # 静态方法 是个啥都不带的普通函数      由对象类调用
    # property属性 是个伪装成属性的方法  由对象调用 但不加括号


    内置函数

    __call__  :  对象()调用这个类中的__call__方法

    class A:
        def __call__(self, *args, **kwargs):
            print('这是call方法')
    a = A()
    print(callable(a))         # 有call方法就是True,没有就是False

    __len__  : 


    __new__ : 实例化的时候,先创建一个空间,有一个指针能指向类 –-> __new,  先调用   __new__,再调用__init__

            # 什么时候执行

            # 为什么要有

            # 单例




    __str__ :























    -----------------------   end -------------------------

    对于一个有思想的人来说,没有地方是荒凉而遥远的
  • 相关阅读:
    vue 拖拽移动(类似于iPhone虚拟home )
    鼠标事件-MouseEvent【转】
    JS快速排序 希尔排序 归并排序 选择排序
    JS 继承
    Centos6 iptables 防火墙设置【转】
    centos6 mongodb 安装
    操作系统中涉及的各种调度算法
    循环队列
    队列
    栈(C++)
  • 原文地址:https://www.cnblogs.com/quanag/p/13097468.html
Copyright © 2011-2022 走看看