Python学习笔记2:类的定义和继承




# 类的定义
格式:
class 类名(父类):
__init(self,参数)
成员方法

成员变量


# 所有类的基础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 position


定义一个鸡类:继承自鸟类
class 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,", words


使用:
summer = 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


附录:

# 内置函数
# dir() 用来查询一个类或对象的属性
# help()用来查阅说明文档


# 序列常用函数
len(s)-元素个数
min(s)-最小的元素
max(s)-最大的元素
sum(s)-求和
s.count(x)-元素x在序列s中的出现次数
s.index(x)-元素x在序列s中第一次出现的下标


# 表(由于定值表的元素师不可变更的)
l.extend(l2)-在表l后添加l2的全部元素
l.append(x)-在l的末尾附加x元素
l.sort()-对l中的元素排序
l.reverse()-将l中的元素逆序
l.pop()-返回:表l的最后一个元素,并在表l中删除该元素
del l[i]-删除该元素

评论关闭