python 类的几种方法(函数)
2015-11-11 13:56
537 查看
python中可以定义类,为面向对象语言。
在定义个class时,可以定义3中类型的方法。包括‘实例方法’、“类方法”,“静态方法”其中不同之处:
python类的方法
1,实例方法
实例方法是最简单的一种方法,定义一个实例方法第一个默认的隐式传参标示调用当前方法的实例:
sayHello方法是实例的方法,所以类调用不到。
2,类方法
用@classmethod装饰的方法是类方法,用类和实例都能访问到,传入的参数第一个是类,不是实例。所以访问不到实例的属性。
3,静态方法
用@staticmethod装饰的方法称为静态方法,和前2种的主要区别是第一个参数不是默认,需要调用者传入。和java中的方法一样,可以用作工具方法。
在定义个class时,可以定义3中类型的方法。包括‘实例方法’、“类方法”,“静态方法”其中不同之处:
类型 | 类访问 | 实例访问 | 意义 |
实例方法 | 不可以 | 可以 | |
类方法 | 可以 | 可以 | |
静态方法 | 可以 | 可以 |
实例方法是最简单的一种方法,定义一个实例方法第一个默认的隐式传参标示调用当前方法的实例:
#encoding:utf-8 #小五 classPerson(object): def__init__(self,name): self.name=name defsyaHello(self): returnself.name+'!hello!' def__str__(self): return'Personname(%s)'%self.name p1=Person('Bob') printp1.syaHello()#可以输出Bob!hello! printPerson.syaHello()#报错:unboundmethodsyaHello()mustbecalledwithPersoninstanceasfirstargument(gotnothinginstead)
sayHello方法是实例的方法,所以类调用不到。
2,类方法
用@classmethod装饰的方法是类方法,用类和实例都能访问到,传入的参数第一个是类,不是实例。所以访问不到实例的属性。
#encoding:utf-8 #小五 classPerson(object): gender='女' def__init__(self,name): self.name=name @classmethod defsayD(self): printself.gender#可以正常输出‘女’ returnself.name#报错:AttributeError:typeobject'Person'hasnoattribute'name' defsayHello(self): returnself.name+'!hello!' def__str__(self): return'Personname(%s)'%self.name p1=Person('Bob') printp1.sayD()
3,静态方法
用@staticmethod装饰的方法称为静态方法,和前2种的主要区别是第一个参数不是默认,需要调用者传入。和java中的方法一样,可以用作工具方法。
#encoding:utf-8
#小五
classPerson(object):
gender='女'
def__init__(self,name):
self.name=name
@staticmethod
defsayD(self):
returnself
defsayHello(self):
returnself.name+'!hello!'
def__str__(self):
return'Personname(%s)'%self.name
p1=Person('Bob')
printp1.sayD('sssss')#可以输出sssss
printPerson.sayD('aa')#可以输出aa
相关文章推荐
- python unittest库 官方网站
- python基础之virtualenv
- (10)python字符格式化
- python安装lib库
- python爬虫(1)
- python中pygame针对游戏窗口的显示方法实例分析(附源码)
- Python核心编程读笔 5: python的序列
- Python - 单继承与多继承
- python基于pygame实现响应游戏中事件的方法(附源码)
- Python基于pygame实现的弹力球效果(附源码)
- Twisted MAC安装
- Python基础(collections)
- Python字符串,元祖,列表,字典
- Python中pygame安装方法图文详解
- 一个倒计时的小工具
- Python基于pygame实现图片代替鼠标移动效果
- python unittest 基本介绍
- Python logging模块详解
- Python 多维字典
- 个人工作中ssd、audio python脚本总结