Python的类(Classes)——学习笔记

Python的类(Classes)

When you write a class, you define the general behavior that a whole category of objects can have.

1.Write Classes and Create Instances

1.1 一个Class的组成部分

最直观的理解:可以把一个class理解为一个生命体,这个生命体有一些特有的attributes(这些attributes定义了它自己)。然后这个生命体可以完成特定动作,即method。
1)特征(attributes)->input features of the class
2)行为(behaviors)->function inside the class

举个例子:一条狗狗的特征是名字和年龄,狗狗能sit和roll over。

class Dog:
        
    def __init__(self,name,age):
        #initialize name and age attributes
        #create an instance
        
        #any variable prefixed with self is available to every method in the class
        self.name = name
        self.age = age
        
    def sit(self):
        print(f"{self.name} is now sitting.")
        
    def rool_over(self):
        print(f"{self.name} rolled over.")

__init__(self, attributes)的作用:create an instance for this class
self的作用:Any variable prefixed with self is available to every method in the class.

#创建一个class的instance
my_dog = Dog("littleblack",5)

print(f"My dog's name is {my_dog.name}.")
#输出 My dog's name is littleblack.
my_dog.sit()
#输出 littleblack is now sitting.

1.2 更新attributes

class Car:
    
    def __init__(self,make,model,year):
        
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
        
    def get_descriptive_name(self):
        
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    
    def read_odometer(self):
        
        print(f"This car has {self.odometer_reading} miles on it.")
    
    #update an attribute
    def update_odometer(self, mileage):
        
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
            
    #increment an attribute
    def increment_odometer(self, miles):
        
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("You can't roll back an odometer!")

update_odometer(self, mileage)可以更新码表,与其他method不同,这里在self后新增了需要pass in的新attribute。

2.The Inheritance of a Class

2.1 关于inheritance的灵魂三问

什么时候需要使用inheritance?

If the class you’re writing is a specialized version of another class you wrote, you can use inheritance.

inheritance有什么用?

When one class inherits from another, it takes on the attributes and methods of the first class.

inheritance的关系

The original class is called the parent class, and the new class is the child class. The child class can inherit any or all of the attributes and methods of its parent class.

2.2 Inheritance例子

电车是汽车的一个子类,所以可以继承Car的attributes和methods。

class ElectricCar(Car):
    
    def __init__(self,make,model,year):
        #the super() function can call a method from the parent class
        super().__init__(make,model,year)
        #specific attributes for an eletric car
        self.battery_size = 40

1)在定义class的时输入要继承的parent class
2)使用super()函数可以调用parent class中的method。比如可使用该方法来继承parent class中的所有attributes。

2.3 Composition

Compostion: break large class into smaller classes that work together

Composition的解释:假如ElectricCar这个class中的arrtribute——battery有一些特殊的method,即这些method是专用于电池的,那我们就可以再单独定义一个class,叫Battery。这样的话就能够使得ElectricCar这个class定义更加简洁清晰。

举个例子:

#Compostion

class Battery:
    
    def __init__(self,battery_size=40):
        self.battery_size = battery_size
        
    def describe_battery(self):
        print(f"This car has a {self.battery_size}-kWh battery.")
        
    def get_range(self):
        if self.battery_size == 40:
            range = 150
        elif self.battery_size == 65:
            range = 225
            
        print(f"This car can go about {range} miles on a full charge.")


class ElectricCar(Car):
    
    def __init__(self,make,model,year,battery_size):
        #the super() function can call a method from the parent class
        super().__init__(make,model,year)
        self.battery = Battery(battery_size)

运行结果:

my_elec = ElectricCar('aito', 'm9-ultra', '2024', 65)
my_elec.battery.get_range()

#输出 This car can go about 225 miles on a full charge.

参考书目:Python Crash Course 3rd Edition

  • 18
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值