首页 > 其他 > 详细

类的常用特征

时间:2016-07-05 20:52:25      阅读:202      评论:0      收藏:0      [点我收藏+]

讲解见代码:

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)

 

  

 

类的常用特征

原文:http://www.cnblogs.com/owasp/p/5644866.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!