Python类

转自 bravezhe http://blog.csdn.net/bravezhe/article/details/7286024

类方法和函数区别

是否有self


类方法变量私有

加双下划线

def __speek(self):


类初始化

def init(self):


类继承

class Chinese(Persion):



Class A(object):

继承object类 使类增加以下功能

staticmethod是静态方法
classmethod是类方法
super是用来返回父类
__new__是一个在__init__之前调用的东西,用来定制class, 这个东西有点复杂,感觉象是元编程了


自己写的一个例子:

module2.py

#coding=utf-8
import module1
class Class2:
        """说明python面向对象的一个小例子,Class2调用Class1的hello方法
        """
        def hello(self):
                print("hello Class2")
                self.obj1.hello()

        def __init__(self):
                self.obj1=module1.Class1()
                print("init Class2")

if __name__=="__main__":
        obj2=Class2()
        print("obj2 type:%s" % type(obj2))
        obj2.hello()

module1.py

class Class1:
        def hello(self):
                print("hello Class1")

运行 python module2.py 得到如下结果,说明调用成功:

init Class2
obj2 type:<type 'instance'>
hello Class2
hello Class1


你可能感兴趣的:(Python类)