如何用python构建一个简单的类

来源:互联网 发布:linux 文件夹读写权限 编辑:程序博客网 时间:2024/05/17 16:03

先给出一个例子

class test:  test_num = 0;  def __init__(self, x = 0, y = 0):    self.x = x    self.y = y    test.test_num += 1  def show_test_num(self):    print "num is %d" % test.test_num  def show_x_y(self):    print "x is %d and y is %d" %(self.x, self.y)test1 = test(1, 2)test2 = test(2, 3)test1.show_x_y()test1.show_test_num()
  1. test_num 是一个类变量, 在所有类的实例之间共享

  2. init 是这个类的构造函数, 其中的x, y都是类的成员变量,(声明一个成员变量要在前面加上self.)

  3. 类的每个函数的第一个参数都是self(或者叫其他名字也行, 并不是关键字), 代表类的实例

原创粉丝点击