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)
运行结果:文章来源:https://www.toymoban.com/news/detail-800615.html
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文章来源地址https://www.toymoban.com/news/detail-800615.html
到了这里,关于Python的类(Classes)——学习笔记的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!