Python学习笔记ucas(lecture 5)(完结!)类和对象

Lecture 5 类和对象

目录

1面向对象程序设计的由来

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

2类和对象

这里写图片描述
这里写图片描述

class Person(object):
    def __init__(self):     # 类的构造函数,用来初始化对象
        self.name = ''
        self.age = 0
    def display(self):      # 类中定义的函数,也称方法
        print(self.name,self.age)

if __name__=='__main__':
    p=Person()     #创建对象
    print(p)
    print(p.age)   #引用对象的属性
    print(p.name)
    p.age = 25
    p.name = 'MaLele'
    p.display()   #引用对象的方法

<main.Person object at 0x0000000001259A58>
0

MaLele 25
这里写图片描述

3属性和方法

这里写图片描述

class Fruit(object):
    price = 0                  # 类属性
    def __init__(self):
        self.color = 'red'     # 实例属性
        zone = 'China'         # 局部变量

if __name__=='__main__':
    print(Fruit.price)         #使用类名调用类变量
    apple = Fruit()            #实例化apple
    print(apple.color)
    Fruit.price = Fruit.price+10  
    print(apple.price)
    banana = Fruit()
    banana.color = 'yellow'
    print(banana.color)
    print(banana.price)

0
red
10
yellow
10
这里写图片描述
这里写图片描述

2、类的方法
分为公有方法、私有方法
Python使用函数staticmethod()或@staticmethod修饰器将普通的函数转换为静态方法

class Fruit(object):
    price = 0                # 定义类变量

    def __inin__(self):
        self.__color = 'red' # 定义私有变量

    def getColor(self):
        print(self.__color)  # 打印私有变量

    @staticmethod            # 使用staticmethod修饰器定义静态方法
    def getPrice():
        print(Fruit.price)

    def __getPrice():        # 定义私有函数
        Fruit.price = Fruit.price + 10
        print(Fruit.price)

    count = staticmethod(__getPrice)   # 使用staticmethod方法定义静态方法

if __name__=="__main__":
    apple = Fruit()    # 实例化apple
    apple.getPrice()   # 使用实例调用静态方法
    Fruit.count()      # 使用类名调用静态方法

    banana = Fruit()
    Fruit.getPrice()
    Fruit.count()

0
10
10
20

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

4继承

这里写图片描述
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值