Python 类
- 类的定义
- 类的方法至少有一个参数self
class MyClass(object):
def fun(self):
print '类的方法'
- 类的实例化 --> 创建对象
obj = MyClass
-
类的属性
- 公有属性: 类内外都能调用的属性
- 私有属性:不能在类外以及被类以外的函数调用,私有属性定义方法:以双下划线开始的成员变量就是私有属性
- 内置属性:系统在定义类的时候默认添加的,由前后双下划线构成,
- dict:类的属性(包含一个字典,由类的数据属性组成)
- doc:类的文档字符串
- name:类名
- module:类定义所在的模块
-
类的方法:类的方法定义跟函数的定义一样,但是需要self作为第一个参数
- 公有方法:在类中类外都能调用的方法
- 私有方法:不能被类的外部调用,私有方法定义:方法前面加上双下划线,
-
类方法:被classmethod()函数处理过,才能被类所调用
In [8]: class Testing(object): ...: def test(self): ...: print('hello test') ...: def test2(self): ...: print('hello test2') ...: pt = classmethod(test) ...: In [9]: Testing.pt() hello test In [10]: Testing.test() ##是不能直接通过类调用类方法的, ------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-372b771144d0> in <module>() ----> 1 Testing.test() TypeError: unbound method test() must be called with Testing instance as first argument (got nothing instead) In [11]: Testing.test2() ------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-f17045d44574> in <module>() ----> 1 Testing.test2() TypeError: unbound method test2() must be called with Testing instance as first argument (got nothing instead)
-
静态方法:相当于“全局函数”,可以被类直接调用,可以被所有实例化对象共享,通过staticmethod()定义,静态方法没有“self”参数。