python3

Head First Python 读书笔记(六)

2018-07-16  本文已影响0人  icessun

类:抽象行为和状态

采用驼峰命名法

class Dog():
    """创建了狗类"""

    def __init__(self, name:str, age:int) -> None:
        '''初始化属性name和age'''
        self.name = name
        self.age = age

    def sit(self) -> None:
        '''模拟小狗蹲下'''
        print(self.name.title()+' is now sitting.')

    def roll_over(self) -> None:
        '''模拟小狗打滚'''
        print(self.name.title()+' rolled over!')


taidi = Dog('taidi', 2)  # 对象实例化
print(taidi.sit())

类中的方法由同一个类创建的所有实例对象所共享,类中的属性不会由同一个类创建的其他对象所共享

单独使用对象名称
>>> type(d) # 对象的类型
<class '__main__.Dog'>
>>> id(d)  # 对象在内存中的地址
92579984
>>> hex(id(d))  # 地址转为十六进制数
'0x584a890'

继承

class Car():
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer = 0

    def get_descriptive_name(self):
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name.title()

    def read_odometer(self):
        print("this car has "+str(self.odometer)+" miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer:
            self.odometer = mileage
        else:
            print('You can`t roll back an odometer!')

    def increment_odometer(self, miles):
        self.odometer += miles

    def fill_gas_tank(self):
        print('this car has fill gas tank!')

# 电动汽车 继承 汽车类
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery_size = 70 # 定义了属于子类的方法和属性

    def describe_battery(self):
        print("this car has a "+str(self.battery_size) + '-KWH battery.')

    def fill_gas_tank(self):
        print('This car doesn`t need a gas tank')

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
# 子类中传入父类作为参数,并且需要调用 super 方法去为父类初始化值
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
class Battery():
    def __init__(self, battery_size=70):
        self.battery_size = battery_size

    def describe_battery(self):
        print('This car has a '+str(self.battery_size)+'-kWh battery.')


class ElectricCar(Car):
    def __init__(self, make, model, year):
        self.battery_size = Battery()  # 类的实例对象作为子类实例属性,默认值为70
        super().__init__(make, model, year)

    def fill_gas_tank(self):
        print('This car doesn`t need a gas tank')


my_tesla = ElectricCar('tesla', 'model s', 2016)

my_tesla.battery_size.describe_battery() # 子类的实例对象的属性去调用Battery的方法
上一篇下一篇

猜你喜欢

热点阅读