Python 类与对象的使用

# Copyright (c)2018, 东北大学软件学院学生
# All rightsreserved
# 文件名称:test.py
# 作   者:孔云
#问题描述:Python类与函数
class Animals():
    #语法规定,在类里定义函数,函数第一个参数必须是self
    def breathe(self):
        print (" breathing")
    def move(self):
        print ("moving")
    def eat (self):
        print ("eating food")
        # Animals子类:Mammals
class Mammals(Animals):
    def breastfeed(self):
        print ("feeding young")
        #Mammals子类:Cats
class Cats(Mammals):
    #__init__函数,类的对象实例化时自运行,用于给新对象赋初值。
    def __init__(self, spots):
        self.spots = spots
    def catch_mouse(self):
        print ("catch mouse")
    def left_foot_forward(self):
        print ("left foot forward")
    def left_foot_backward(self):
        print ("left foot backward")
    def dance(self):
        #类里定义函数,如果调用自身和父类的函数与变量,须用self.引导,写为self.函数名或self.变量名
        self.left_foot_forward()
        self.left_foot_backward()
        self.left_foot_forward()
        self.left_foot_backward()
kitty=Cats(10)
#对象调用类里的变量,要用对象.变量名
print (kitty.spots)
#对象调用父类或自身类里的函数,要用对象.函数名
kitty.dance()
kitty.breastfeed()
kitty.move()
运行结果如下:

注释:

Python 中虽然没有访问控制的关键字,例如 private、 protected 等等。但是,在 Python 编码中,有一些约定来进行访问控制。
单下划线、 双下划线、 头尾双下划线说明如下:
_foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *
__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
__foo__: 头尾双下划线定义的是特列方法,类似 __init__() 之类的。



猜你喜欢

转载自blog.csdn.net/u012369559/article/details/79947448
今日推荐