python的一些有关定义的语法细节
2016-03-07 20:08
309 查看
1.在class中定义方法
self 实例方法名称前面可以dual underline__an_self_method
但类方法(没有self)不能双下划线,只能加单下划线
2.@staticmethod与@classmethod
@staticmethod使得实例也可以调用类方法,但实质上是使得既与class无关,又与self无关的函数能够放在类里,作为实例属性、类属性调用
#最初 class T: def bb(self): T.a(2,4) def a(c,d): print(c+d) >>>T.a(1,2) 3 >>>T().a(1,2) TypeError: a() takes 2 positional arguments but 3 were given #包装为实例的静态方法后 class T: def bb(self): T.a(2,4) @staticmethod def a(c,d): print(c+d) >>>T().a(1,2) 3
@classmethod
作为类属性,而不是实例属性
@classmethod def withdraw(cls,amount):#cls default class method like self pass
参考>http://www.wklken.me/posts/2013/12/22/difference-between-staticmethod-and-classmethod-in-python.html
3.时间字符串格式化
#2013-05-02-23:22:30 when=datetime.datetime.strptime('20130502T23:22:30','%Y%m%dT%H:%M:%S') >>>when datetime.datetime(2013, 5, 2, 23, 22, 30)
4.标识符命名
#_xx :内部变量 #__xx :据说是内部方法,但起码在python3.4里,果然只能作为实例方法,连类方法都不行 #__xx__ :pass #xx_ :如果与关键字重复
参照一篇相对于本条,大约5年的知乎文
https://www.zhihu.com/question/19754941
相关文章推荐
- python小点心--获取汉子拼音首字母
- python小点心-logging 日志模块
- Python使用mechanize模拟浏览器
- Python爬虫经验
- python模块之 - logging
- python小点心--内存文件映射
- python 登录并爬取淘宝信息
- 获取腾讯企业邮箱通讯录python脚本(带登录功能)
- python小点心--struct 封装变长字符串
- mac下更新pip时提示OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pip-8.0.2-py2.
- python格式化输出dict等集合对象
- [LeetCode]题解(python):105-Construct Binary Tree from Preorder and Inorder Traversal
- Python django学习
- [LeetCode]题解(python):104-Maximum Depth of Binary Tree
- [LeetCode]题解(python):103-Binary Tree Zigzag Level Order Traversal
- C\C#\Java\Python 基本数据类型比较
- [LeetCode]题解(python):102- Binary Tree Level Order Traversal
- windows系统下Python环境的搭建
- [LeetCode]题解(python):101-Symmetric Tree
- 【python】编程语言入门经典100例--24