Python类的结构python
class 类名: 成员变量 成员函数 class MyClass(): first = 123 def fun(self): print "I am function"
对象的属性和方法与类中的成员变量和成员函数对应程序员
if __name__ == "__main__": myClass = MyClass() #建立类的一个实例
构造函数__init__web
class Person: def __init__(self, name, lang, website): self.name = name self.lang = lang self.website = website
子类、父类和继承编程
# 抽象形状类 class Shape: # 类的属性 edge = 0 # 构造函数 def __init__(self, edge): self.edge = edge # 类的方法 def getEdge(self): return self.edge # 抽象方法 def getArea(self): pass #三角形类,继承抽象形状类 class Triangle(Shape): width = 0 height = 0 # 构造函数 def __init__(self, width, height): #调用父类构造函数 Shape.__init__(self, 3) self.width = width self.height = height #重写方法 def getArea(self): return self.width * self.height / 2 #四边形类,继承抽象形状类 class Rectangle(Shape): width = 0 height = 0 # 构造函数 def __init__(self, width, height): #调用父类构造函数 Shape.__init__(self, 4) self.width = width self.height = height #重写方法 def getArea(self): return self.width * self.height triangle = Triangle(4,5); print triangle.getEdge() print triangle.getArea() rectangle = Rectangle(4,5); print rectangle.getEdge() print rectangle.getArea()
python支持多继承,但不推荐使用数组