【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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值