Python编程从入门到实践~类

创建Dog 类

方法__init__(),Python 自动调用,约定!!!


#创建Dog 类
class Dog:

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

	def sit(self):
		print(f"{self.name} is now sitting.")

	def roll_over(self):
		print(f"{self.name} rolled over.")


#根据类创建实例
my_dog = Dog('Willie', 6)

#访问属性
print(f"My dog's name is {my_dog.name}")

#调用方法
my_dog.sit()

使用类和实例

class Car(object):
	"""docstring for 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.")

	def update_odometer(self, mileage):
		self.odometer_reading = mileage
		

my_car = Car('audi', 'a4', 2019)
print(my_car.get_descriptive_name())


##直接修改属性值
my_car.odometer_reading = 55
my_car.read_odometer()


##通过方法修改属性的值
my_car.update_odometer(66)
my_car.read_odometer()

继承

class Car(object):
	"""docstring for 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.")

	def update_odometer(self, mileage):
		self.odometer_reading = mileage

	def fill_gas_tank(self, volume):
		self.volume = volume


class ElectricCar(Car):
	"""docstring fos ElectricCar"""
	def __init__(self, make, model, year, battery_size=75):
		#初始化父类的属性
		super().__init__(make, model, year)
		#子类定义属性
		self.battery_size = battery_size
	
	#子类定义方法	
	def describe_battery(self):
		print(f"This car has a {self.battery_size}-kWh battery.")

	#覆盖父类方法
	def fill_gas_tank(self, volume):
		print("This car does't need a gas tank.")

my_tesla = ElectricCar('tesla', 'model s', '2019')
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank(50)

导入类

#导入类
from car import Car, ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2019)
my_tesla = ElectricCar('tesla', 'roadster', 2020)


#导入模块
import car
my_beetle = car.Car('volkswagen', 'beetle', 2019)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值