成员变量
# 所有类的基础object
# 私有方法和变量使用__开头
例如:定义一个鸟类
class Bird(object):
__have_feather = True # 私有属性:是否有羽毛
way_of_reproduct = "egg" # 公有属性:繁殖方式
def move(self, dx, dy): # 公有方法
position = [0,0]
position[0] = position[0] + dx
position[1] = position[1] + dy
return positionclass Chicken(Bird):
way_of_move = "walk" # 添加一个公有属性 class Oriole(Bird):
way_of_move = "fly" # 添加一个公有属性
class happyBird(Bird):
def __init(self, words): # 构造函数
print "We are happy birds,", wordssummer = Bird() print "after move:",summer.move(5,8) happy = happyBird()
class Human(object):
laugh = "hahaha" # 公有属性
def __init__(self, gender): # 构造函数
self.gender = gender # 定义并初始化公有属性
def __show_laugh(self): # 私有方法
print self.laugh
def show_laugh_twice(self): # 公有方法
self.show_laugh() # 调用私有方法
self.show_laugh() # 调用私有方法man = Human("male")
man.show_laugh_twice()
print man.gender
附录:
# 内置函数原文:http://blog.csdn.net/xufeng0991/article/details/39585139