python.day.10——面向对象(二)

一、初始化

  •  初始化函数:每一个实例
  •  def __init__(self):
  • 1:他跟普通函数一样,有关键字self
  • 2: 他可以带位置参数,默认参数
  • 3: 他没有返回值
  • 4:他的作用:每一个实例创建的时候,都会自动带上一个init函数里的参数
  • 5:提高复用性(不要写死,可定制)
class User:
    def __init__(self, name, content): # 创建实例的时候,定义初始化的一些属性值
        self.name = name
        self.content = content

    def describe_user(self):
        print("该用户的名字为:", self.name)

    def greet_user(self):
        # 个性化问候
        print(self.content, self.name)

user_01 = User('natu','我好喜欢你啊')
user_01.greet_user()
  • 注意:当这个类必须具备某些属性,就放到初始化__init__(self)中去

二、继承

  • 继承: 全部继承 部分继承 多继承 超继承
    import from...import 类与模块  
  • 全继承:用的比较少
class User:
    def __init__(self, name, content): # 创建实例的时候,定义初始化的一些属性值
        self.name = name
        self.content = content
    def describe_user(self):
        print("该用户的名字为:", self.name)
    def greet_user(self):
        # 个性化问候
        print(self.content, self.name)

# 这就是我们的测试程序的入口  
if __name__ == '__main__': #python 程序的入口
    user_01 = User('natu', '我好喜欢你啊')
    user_01.greet_user()

控制台输出:
我好喜欢你啊 natu
#全部继承
# 导入类  
#import untitled.class_day08.tast_01    #第一种导入:直接导入模块(如果该模块中没有程序入口函数则会运行当前模块)
from untitled.class_day08.tast_01 import User # 具体到类名

class SuperUser(User): # 完全继承 全部继承
    pass

qq = SuperUser('那年那兔那些事儿', '老子就是喜欢你:')
qq.greet_user()

控制台输出:
老子就是喜欢你: 那年那兔那

super是关键字:根据传进来的类,找到父类,再去调用父类里面的方法

下面是我创建的一个类:

class Restaurant:

    def __init__(self, restaurant_name, cooking_type):
        self.restaurant_name = restaurant_name
        self.cooking_type = cooking_type

    def describe_restaurant(self):
        print(self.restaurant_name + "的营业范围是:" + self.cooking_type)

    def open_restaurant(self):
        print(self.restaurant_name + "该餐馆正在营业中")
# 继承Restaurant
from day.class_day07.test_01 import Restaurant

class SubRestaurant(Restaurant):

    def __init__(self, restaurant_name, cooking_type, discounts, pay_moneys):
        super(SubRestaurant, self).__init__(restaurant_name, cooking_type)
        self.discounts = discounts
        self.pay_moneys = pay_moneys

    def discount(self):
        print(self.restaurant_name + "的折扣为:" + self.discounts)

    def pay_money(self):
        print("最终支付价格为:%s" % self.pay_moneys)
# 超继承(SubRestaurant)
from day.class_day07.test_02 import SubRestaurant

class SuperRestaurant(SubRestaurant):
    def __init__(self, restaurant_name, cooking_type, discounts, pay_moneys, contents):
        SubRestaurant.__init__(self, restaurant_name, cooking_type, discounts, pay_moneys)
        self.content = contents

    def open_restaurant(self):
        print("优惠信息宣传:" + self.content)

if __name__ == '__main__':
    restaurant_2 = SuperRestaurant("眼镜米线", '米线、米粉、酸辣粉、混沌', '9折', 126, '新店开张全面优惠呢,打9折,更多惊喜送不停')
    restaurant_2.describe_restaurant()
    restaurant_2.open_restaurant()
    restaurant_2.discount()
    restaurant_2.pay_money()

猜你喜欢

转载自www.cnblogs.com/Rosay9204781/p/9173821.html
今日推荐