返回列表 发帖

[转载教程] 有趣的Python 3: 第一个类

既然Python是面向对象的语言,自然是支持类的定义的。现在就动手,来定义我们的第一个类:
记得吗?Python是以缩进来界定代码块的位置,而不是靠‘{’之类的符号。

class MyClass:
    "A simple example class"
    i = 12345 #this is a field
    def __init__(self):
        self.perInstVar = 'a'
    def f(self):
        return 'hello world'
x = MyClass()
print x.f()COPY


我们可以看到下面几点:
【1】 class的documentation comment是类似javadoc的东西
【2】 class包含data field和member function。 其中i是class variable,就是static的变量。而__init__()内部定义的是per instance variable。 __init__()是个特殊的函数,会在对象被构造的时候被调用。
【3】单行注释的写法
【4】member function的第一个参数一定是self,类似java里的this。这个需要显示传入,和java/c++是不一样的
【5】 可以看到class的初始化和调用方式

原文:http://bbs.chinaunix.net/thread-554818-1-1.html

类的文档注释显示方法,__doc__是类的其中一个属性
print(MyClass.__doc__)COPY
或者
help(MyClass)COPY

TOP

返回列表