遇到问题
目前在学习《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.分类函数名()
即可将函数中的属性参数传入类属性,后续只需要对类进行实例化工作后,即可作为‘类属性’进行直接调用,维护起来比较方便。