【hisword2017】Python Notebook - 对象,你好!

对象:
万物皆对象
对象 = 类 + 实例
1,类的创建-属性和方法的定义
2,类的实例化- 实例属性和方法的调用
3,类的特殊参数 self
4, 类的特殊方法: inti
5, 类的继承
6,类的多层继承
7,类的多重继承

代码:
1.类的创建

# 类的创建- 属性和方法的定义
# 1,class 关键字
# 2,类名首字母大写
# 3,类定义后加冒号
# 4,类中定义的变量为属性
# 5, 类中定义的函数叫方法
# 6,类中的方法叫实例方法

class Vehicle:
	motor = True
	def start(self):
		print('The vehicle is starting...')

class Car:
	name = 'car'
	motor = True
	wheel = 4
	size  = 'small'
	def start(self):
		print('The car is starting...')

2.类的实例化

# 类的实例化 = 类的调用
# 实例名 = 类名()
# 实例名.方法
# 实例名.属性
mycar = Car()
print(mycar.name)
mycar.start()

mycar2 = Car()
print(mycar2.name)
mycar2.start()

# Result:
# car
# The car is starting...
# car
# The car is starting...

3.类的特殊参数self

# 把self理解为实例
class BMW:
	name = 'BMW'
	motor = True
	wheel = 4
	size  = 'small'
	def start(self):
		print(self.name + ' car is starting...')
	def selfdrive(self):
		print('BMW Car is beginning Selfdrive Mode!')
		self.start()

mycar = BMW()
mycar.start()
mycar.selfdrive()

# Result:
# BMW car is starting...
# BMW Car is beginning Selfdrive Mode!
# BMW car is starting...

4.类的特殊方法: inti

# 类调用时自动运行
class Car: 
	def __init__(self):
		print('Car is initiating...')
	
mycar = Car()
# Result:
# Car is initiating...

# 初始化传参
class BMW():
	def __init__(self,type,price):
		self.type = type
		self.price = price
	def price_prt(self):
		print(self.type + "'s price is:" + str(self.price))

mycar = BMW('X1',250000)
mycar.price_prt()

# Result:
# X1's price is: 250000		

5, 类的继承

# class A(B):
# A 子类名
# B 父类名

# 父类
class Carfamily:
	motor = True
	wheel = 4
	def start(self):
		print('Car is starting...')

# 子类
class BMW(Carfamily):
	pass

mycar = BMW()
print(mycar.wheel)
mycar.start()

# Result:
# Car is starting...

6, 类的多层继承

class Vehicle:
	wheel = 2
class Car(Vehicle):
	wheel = 4
	color = 'black'
class BMW(Car):
	pass

mycar = BMW()
print(mycar.wheel)
print(mycar.color)

# Result:
# 4
# black

7, 类的多重继承

class Vehicle:
	wheel = 2
	motor = True
class Car(Vehicle):
	wheel = 4
	color = 'black'
class BMW(Car,Vehicle):
	pass

mycar = BMW()
print(mycar.wheel)
print(mycar.motor)
print(mycar.color)

# Result:
# 4
# True
# black

你可能感兴趣的:(hisword2017)