python基础之类

类的示例

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('willie',6)   #实例化类
your_dog = Dog('luck',3)
print("My dog name is " + my_dog.name.title() + '.')    #调用类的属性
print("My dog is " + str(my_dog.age) + ' years old.')
my_dog.sit()    #调用类的方法
my_dog.roll_over()

print("\nYour dog name is " + your_dog.name.title() + '.')
print("Your dog is " + str(your_dog.age) + ' years old.')
your_dog.sit()
your_dog.roll_over()

类的实例和操作

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 = str(self.year) + ' ' + self.make + " " + self.model
		return long_name.title()

	def read_opometer(self):
		print("This car has " + str(self.odometer_reading) + " miles on it.")

	def update_odometer(self,mileage):    #修改类属性
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print('You can not roll back an odometer')

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

my_new_car = Car('audi','a8',2020)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_opometer()
my_new_car.increment_odometer(100)
my_new_car.read_opometer()

类的继承

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 = str(self.year) + ' ' + self.make + " " + self.model
		return long_name.title()

	def read_opometer(self):
		print("This car has " + str(self.odometer_reading) + " miles on it.")

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

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

	def fill_gas_tank(self):
		print("This is car")

class ElectricCar(Car):   #继承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 does not need a gas tank!")
		
my_tesla = ElectricCar('tesla','model',2021)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()

posted @ 2020-10-04 20:11  Harry_666  阅读(110)  评论(0编辑  收藏  举报