面向对象编程(OOP)—— 以python为例

面向对象编程(Object Oriented Programming,OOP)是一种计算机编程框架。其基本特征是封装、继承和多态。核心概念是类和对象。具有易重用、易扩展、灵活等优点。类是对客观世界的抽象,包括静态属性的数据、数据属性和对数据的操作,对象是类的实例化。对象间通过消息传递进行相互通信,来模拟现实实体间的联系。在面向对象的程序设计中,对象是组成程序的基本模块。

封装:指将数据和对数据的一切操作封装在一个“模块”中,也就是一个类中。

继承:类之间可以相互继承,子类能够使用(复制)父类的属性和方法,并且也可以覆盖(重写)父类方法。

多态:多个不同的对象同时接收到一个相同的消息,表现出来的动作各不相同。

缺点:运行效率低,类库庞大,类库可靠性

例子:python

python中创建类并实例化一个对象:

#创建一个冰淇淋小店的类
class Restaurant():
    '''冰淇淋小店类'''
    def __init__(self,restaurant,cuisine_type):
        self.restaurant = restaurant
        self.cuisine_type = cuisine_type
        
    def describe_restaurant(self):
        print("the restaurant's name is " + self.restaurant)
        print("the cuisine_type of this restaurant is "+self.cuisine_type)
        
    def open_restaurant(self):
        print(self.restaurant +"now is open, welcome.")

#创建一个冰淇淋小店中冰淇淋价格的类        
class Price():
    '''冰淇淋价格'''
    def __init__(self,icec):
        self.icec = icec
    
    def price(self):
        if self.icec == "orange":
            print("the price of orange is 20")
        elif self.icec == "apple":
            print("the price of apple is 10")
        elif self.icec == "banana":
            print("the price of banana is 13")
        else:
            print("the price of grape is 25")


#继承父类        
class IceCreamStand(Restaurant):
    def __init__(self,restaurant,cuisine_type,icec):
        super().__init__(restaurant,cuisine_type)
        self.flavors = ["orange","apple","banana","grape"]
        self.p = Price(icec)
    
    def ice(self):
        print("this IceCreamStand has many types ice-cream,such as: ")
        print(self.flavors)
        
    def pr(self):
        Price.price(self.p)
        
    
#实例化对象        
ic = IceCreamStand(restaurant="gegegice",cuisine_type="helen",icec="orange")
print('查看restaurant属性——',ic.restaurant,sep='\n')
print('\n调用类中的describe_restaurant方法——')
ic.describe_restaurant()
print('\n调用类中的pr方法——')
ic.pr()

结果:

 

 

 

 

参考百度百科

https://baike.baidu.com/item/面向对象程序设计/24792?fromtitle=%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B&fromid=254878&fr=aladdin

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值