python对类属性进行函数分类后的调用方法(类内传参)

遇到问题

目前在学习《Python编程:从入门到实践》中的实例,根据书中指引,对游戏的Settings类下的属性进行静态和动态的分类。

分类前的代码:

class Settings():
	def __init__(self):
		'''initialize the static setttings for the game'''
		#screen settings
		self.screen_width = 1200
		self.screen_height = 800
		self.bg_color = (230,230,230)
		#ship settings
		self.ship_limit = 3
		#the setting of the bullet
		self.bullet_width = 3
		self.bullet_height = 15
		self.bullet_color = 60,60,60
		self.bullets_allowed = 99
		
		self.fleet_drop_speed = 10
		self.ship_speed_factor = 1.5
		self.bullet_speed_factor = 3
		self.alien_speed_factor = 1
		#fleet_direction为1 表示向右移,-1表示向左移
		self.fleet_direction = 1
class Bullet(Sprite):
	def __init__(self,ai_settings,screen,ship):
		#create a bullet object at the position of the ship
		super(Bullet,self).__init__()
		--snip--
		self.speed_factor = ai_settings.bullet_speed_factor

在项目的主文件中已经创建了Settings类的实例并将其命名为ai_settings,所以这里直接调用bullet_speed_factor属性。

分类后的代码:

class Settings():
	def __init__(self):
		'''initialize the static setttings for the game'''
		#screen settings
		self.screen_width = 1200
		self.screen_height = 800
		self.bg_color = (230,230,230)
		#ship settings
		self.ship_limit = 3
		#the setting of the bullet
		self.bullet_width = 3
		self.bullet_height = 15
		self.bullet_color = 60,60,60
		self.bullets_allowed = 99
		
		self.initialize_dynamic_settings()

	def initialize_dynamic_settings(self):
		'''initialize settings that change as the game progress'''
		self.ship_speed_factor = 1.5
		self.bullet_speed_factor = 3
		self.alien_speed_factor = 1
		#fleet_direction为1 表示向右移,-1表示向左移
		self.fleet_direction = 1
class Bullet(Sprite):
	def __init__(self,ai_settings,screen,ship):
		#create a bullet object at the position of the ship
		super(Bullet,self).__init__()
		--snip--
		self.speed_factor = ai_settings.bullet_speed_factor

运行后报错,显示提示信息

self.speed_factor = ai_settings.bullet_speed_factor
AttributeError: ‘Settings’ object has no attribute ‘bullet_speed_factor’

起初是认为分类后’bullet_speed_factor’不在Settings类属性内,所以无法通过ai_settings.bullet_speed_factor调用,后来发现是变量名打多了一个字母,导致前后不一致造成的问题。

回看代码发现,在Setttings类的属性中定义self.initialize_dynamic_settings(),可以将Settings类下属的initialize_dynamic_settings函数的属性直接传递给Settings类,作为其类属性。

总结

这是一个基本的传参问题,当需要对类属性进行分类时,可以将各类属性放入不同的函数中,并在类的属性定义中写入self.分类函数名()即可将函数中的属性参数传入类属性,后续只需要对类进行实例化工作后,即可作为‘类属性’进行直接调用,维护起来比较方便。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值