python中类的基本用法

#encoding:utf-8

#创建类
class Dog():

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        print(self.name.title() + " rolled over!")

#类的实例化
my_dog = Dog('whie', 6)
my_dog.sit()
my_dog.roll_over()

#汽车类
class Car():
    def __init__(self, make, model, year):
        """初始化汽车属性"""
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        """返回整洁的描述性信息"""
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

my_new_car = Car('audi', 'a4', '2016')
print(my_new_car.get_descriptive_name())

#继承
class ElectricCar(Car):
    '''电动汽车'''
    def __init__(self, make, model, year):
        '''初始化父类的属性'''
        super().__init__(make, model, year)

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())

#餐馆类
class Restaurant():
    def __init__(self, restaurant_name, cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self):
        print(self.restaurant_name + ' ' + self.cuisine_type)

    def open_restaurant(self):
        print("正在营业")
print("\n")
restaurant = Restaurant('面条店','烹煮')
restaurant.describe_restaurant()
restaurant.open_restaurant()


#冰淇淋类
#super()是一个特殊函数,帮助python将父类和子类关联起来,
class IceCreamStand(Restaurant):        #继承餐馆类
    def __init__(self, restaurant_name, cuisine_type):
        super().__init__(restaurant_name, cuisine_type)
        self.flavors = []

    def show_flavors(self):
        for flavor in self.flavors:
            print(flavor)
print("\n")
icecreamstand = IceCreamStand('冰激凌店', '冷冻食品')
icecreamstand.describe_restaurant()
print("冰激凌口味如下所示:")
icecreamstand.flavors = ['草莓', '芒果', '西瓜']
icecreamstand.show_flavors()


class cat:
    def __del__(self):
        print("hahaha")

a = cat()
b = a

# del a
#del b  #当所有的对象都不指向定义时分配的内存时,才会彻底删除
print("="*20)


#多继承
class Base:
    def test(self):
        print("---Base---")

class A(Base):
    pass
    # def test(self):
    #     print("---A---")

class B(Base):
    def test(self):
        print("---B---")

class C(A, B):
    pass
    # def test(self):
    #     print("---C----")

c = C()
c.test()
print(C.__mro__)    #打印调用C函数如果出现同名时,调用函数的优先级
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值