zoukankan      html  css  js  c++  java
  • 类的常用特征

    讲解见代码:

    1、__call__()方法、__repr__()方法、静态方法、类方法、属性方法。

    #!/usr/bin/env python2
    # -*- coding:utf-8 -*-
    __author__ = 'DSOWASP'
    
    
    class B(object):
        def __init__(self):
            pass
    
    
    class A(object):
        def __init__(self):
            self.name = "ds"
        age = 18
    
        # 实例()时调用
        def __call__(self, *args, **kwargs):
            print("call")
            return B()
    
        # print(实例)时调用
        def __repr__(self):
            return "__repr__"
    
        # 类方法,只能访问类变量,不能访问实例变量
        @classmethod
        def talk(cls):
            print(cls.age)    # 不能访问self.name
    
        # 静态方法不访问实例变量和类变量,实例.静态方法()时,不会自动传入的id。一个方法不要访问了类和实例变量,但类
        # 又要用这个方法时可以定义为静态方法。
        @staticmethod
        def walk(cmd):
            print("the cmd is :%s"% cmd)      # 不访问self.name和A.age,
    
        # 将方法转为属性,方法他时,不带括号。实例.方法。只有输出,但不接收输入时可以使用。
        @property
        def shout(self):
            print("shout:%s"%self.name)
            return 18
    
        # 这个property.setter装饰的方法必须是被property装饰过的方法。
        # 否则报错:TypeError: descriptor 'setter' requires a 'property' object but received a 'function'
        @shout.setter
        def shout(self,arg):
            print("shout:%s, %s"%(self.name,arg))
            return 18
    a = A()
    a.walk("uptime")
    b = a.shout
    a.shout = 20
    print(b)
    

      

  • 相关阅读:
    pyqt5 Button.click 报错:argument 1 has unexpected type 'NoneType'
    numpy 数组相减
    python 神经网络包 NeuroLab
    xgboost 和GBDT的区别
    stacking
    GBDT
    bp神经网络
    dataframe.isnull()函数, DatetimeIndex,黄包车代码155行
    【Linux】相关概念以及常用命令
    【Hive】优化策略
  • 原文地址:https://www.cnblogs.com/owasp/p/5644866.html
Copyright © 2011-2022 走看看