您的位置:首页 > 其它

类的常用特征

2016-07-05 20:03 260 查看
讲解见代码:

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)


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: