Lesson 13

  • Python Begginer, Level 2, Lesson 12, v1.0.0, 2016.12 by David.Yi
  • v1.1, 2020.5.4 edit by David Yi

本次内容要点

  • 面向对象的编程之四
    • 类属性
    • 类属性安全的访问方法
  • 字符串应用
  • 复习

In [1]:
# 进一步优化
# 加入类属性,npc_count, 计算创建了多少 npc 
# v1.0.13

# npc 的属性字典
npc_dict = {'soldier':{'weapon':'sword', 'blood':1000, 'level':1}, 'wizard':{'weapon':'staff', 'blood':800, 'level':1}}
# fight output 字典
fight_output_dict = {'fight_common':{'name':'Fight Common','blood':-100}, 
                    'sword_fight':{'name':'Sword Fight!','blood':-200},
                    'staff_magic':{'name':'Staff Magic!','blood':-300}}

# NPC 类
class NPC(object):
    
    npc_count = 0
        
    # 初始化 NPC 的属性
    def __init__(self, name):
        self.name = name
        
        # 将类名称转换为全部小写
        self.npc_type = (type(self).__name__).lower()
        
        print('')
        print(self.npc_type, 'NPC created!')
        
        # 初始化值统一放在 NPC 类中
        # 从 npc_dict 中读出
        # weapon_list 保存武器内容
        self.weapon =  npc_dict.get(self.npc_type).get('weapon')
        self.blood = npc_dict.get(self.npc_type).get('blood')
        self.level = npc_dict.get(self.npc_type).get('level')
        
        # npc 计数器 +1 
        NPC.npc_count += 1 
               
    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        print('name:', self.name)
        print('weapon:', self.weapon)
        print('blood:', self.blood)
        print('level:', self.level)
    
    # 定义方法 - 通用攻击
    # fight 的内容从外部读入
    @classmethod
    def fight_common(cls):
        return (cls.__name__, 'blood' , NPC.fight_output('fight_common'))
    
    # 静态方法 - 战斗输出
    # 从外部数据读入战斗输出的值
    @staticmethod
    def fight_output(fight_type):
        name = fight_output_dict.get(fight_type).get('name')
        output = fight_output_dict.get(fight_type).get('blood')
        return (name,output)  
        
# 战士 Soldier 类
class Soldier(NPC):
            
    # soldier 自己的战斗方法
    def sword_fight(self):
        return ('Soldier', 'blood' , NPC.fight_output('sword_fight'))        
        
# 巫师 Wizard 类
class Wizard(NPC):
    
    # wizard 自己的战斗方法
    def staff_magic(self):
        return ('Wizard', 'blood' , NPC.fight_output('staff_magic')) 

# 执行代码
    
s = []

for i in range(2):
    n = Soldier('AA' + str(i))
    n.show_properties()
    s.append(n)
    
for i in range(2):
    n = Wizard('CC' + str(i))
    n.show_properties()
    s.append(n)


print('\nBegin Fighting:')
print(s[1].fight_common())
print(s[1].sword_fight())
print(s[2].fight_common())
print(s[2].staff_magic())
# 查看 npc 数量
print('\nnpc count: ', NPC.npc_count)


soldier NPC created!
name: AA0
weapon: sword
blood: 1000
level: 1

soldier NPC created!
name: AA1
weapon: sword
blood: 1000
level: 1

wizard NPC created!
name: CC0
weapon: staff
blood: 800
level: 1

wizard NPC created!
name: CC1
weapon: staff
blood: 800
level: 1

Begin Fighting:
('Soldier', 'blood', ('Fight Common', -100))
('Soldier', 'blood', ('Sword Fight!', -200))
('Wizard', 'blood', ('Fight Common', -100))
('Wizard', 'blood', ('Staff Magic!', -300))

npc count:  4

In [2]:
# 类变量容易引起问题,每个实例会和类拥有同名的类变量
print(s[0].name)
s[0].npc_count += 1
print('npc count:',s[0].npc_count)
print(NPC.npc_count)


AA0
npc count: 5
4

In [3]:
# 进一步优化
# 将类属性修改为私有,__npc_count, 并通过方法来获得创建了多少 npc 
# v1.0.14

# npc 的属性字典
npc_dict = {'soldier':{'weapon':'sword', 'blood':1000, 'level':1}, 'wizard':{'weapon':'staff', 'blood':800, 'level':1}}
# fight output 字典
fight_output_dict = {'fight_common':{'name':'Fight Common','blood':-100}, 
                    'sword_fight':{'name':'Sword Fight!','blood':-200},
                    'staff_magic':{'name':'Staff Magic!','blood':-300}}

# NPC 类
class NPC(object):
    
    __npc_count = 0
        
    # 初始化 NPC 的属性
    def __init__(self, name):
        self.name = name
        
        # 将类名称转换为全部小写
        self.npc_type = (type(self).__name__).lower()
        
        print('')
        print(self.npc_type, 'NPC created!')
        
        # 初始化值统一放在 NPC 类中
        # 从 npc_dict 中读出
        # weapon_list 保存武器内容
        self.weapon =  npc_dict.get(self.npc_type).get('weapon')
        self.blood = npc_dict.get(self.npc_type).get('blood')
        self.level = npc_dict.get(self.npc_type).get('level')
        
        # npc 计数器 +1 
        NPC.__npc_count += 1 
    
    # 显示 npc 数量方法
    @staticmethod
    def get_npc_count():
        return NPC.__npc_count
               
    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        print('name:', self.name)
        print('weapon:', self.weapon)
        print('blood:', self.blood)
        print('level:', self.level)
    
    # 定义方法 - 通用攻击
    # fight 的内容从外部读入
    @classmethod
    def fight_common(cls):
        return (cls.__name__, 'blood' , NPC.fight_output('fight_common'))
    
    # 静态方法 - 战斗输出
    # 从外部数据读入战斗输出的值
    @staticmethod
    def fight_output(fight_type):
        name = fight_output_dict.get(fight_type).get('name')
        output = fight_output_dict.get(fight_type).get('blood')
        return (name,output)  
        
# 战士 Soldier 类
class Soldier(NPC):
            
    # soldier 自己的战斗方法
    def sword_fight(self):
        return ('Soldier', 'blood' , NPC.fight_output('sword_fight'))        
        
# 巫师 Wizard 类
class Wizard(NPC):
    
    # wizard 自己的战斗方法
    def staff_magic(self):
        return ('Wizard', 'blood' , NPC.fight_output('staff_magic')) 

# 执行代码
    
s = []

for i in range(2):
    n = Soldier('AA' + str(i))
    n.show_properties()
    s.append(n)
    
for i in range(2):
    n = Wizard('CC' + str(i))
    n.show_properties()
    s.append(n)


print('\nBegin Fighting:')
print(s[1].fight_common())
print(s[1].sword_fight())
print(s[2].fight_common())
print(s[2].staff_magic())
# 查看 npc 数量
print('\nnpc count: ', NPC.get_npc_count())


soldier NPC created!
name: AA0
weapon: sword
blood: 1000
level: 1

soldier NPC created!
name: AA1
weapon: sword
blood: 1000
level: 1

wizard NPC created!
name: CC0
weapon: staff
blood: 800
level: 1

wizard NPC created!
name: CC1
weapon: staff
blood: 800
level: 1

Begin Fighting:
('Soldier', 'blood', ('Fight Common', -100))
('Soldier', 'blood', ('Sword Fight!', -200))
('Wizard', 'blood', ('Fight Common', -100))
('Wizard', 'blood', ('Staff Magic!', -300))

npc count:  4

字符串处理

字符串是程序中经常碰到的数据类型,字符串的很多处理和 list 有点像,但也有些区别


In [4]:
# 判断是否是字母

s1 = 'abcde'
s2 = '12'
s3 = '12s'
print(s1.isalpha())
print(s2.isalpha())
print(s3.isalpha())


True
False
False

In [5]:
# 判断是否是字母、是否是数字

s1 = 'abcde'
s2 = '12'
s3 = '12s'
print(s1.isalpha())
print(s2.isdigit())
print(s3.isalpha())


True
True
False

In [11]:
# 判断是否是小写

s1 = 'abc'
print(s1.islower())
print(''.islower())


True
False

In [7]:
# 判断是否是大写 

s1 = 'ABC'
print(s1.isupper())


True

In [8]:
# 是否字母数字混合

s1 ='123abc'
print(s1.isalnum())


True

In [5]:
# 字符串查找

s1 = 'What is your name'
if s1.find('your') != -1:
    print('find it')
    print(s1.find('your'))


find it
8

In [10]:
# 字符串查找的另外一种方式

s1 = 'What is your name'
if 'your' in s1 != -1:
    print('find it')


find it

In [11]:
# 字符串替换

s1 = 'What is your name'
s2 = s1.replace('your', 'my')
print(s2)


What is my name

In [19]:
# 字符串切片

s1 = 'abcdef'
s2 = s1[::-1]
print(s2)


fedcba

In [13]:
# 字符串和列表的转换

s1 = ' a b c  d e f'
s2 = s1.split()
s3 = s1.split(' ')
print(s2)
print(s3)


['a', 'b', 'c', 'd', 'e', 'f']
['', 'a', 'b', 'c', '', 'd', 'e', 'f']

In [14]:
# 字符串转换为小写、大写

s1 = 'aBCdef'
print(s1.lower())
print(s1.upper())


abcdef
ABCDEF

In [22]:
# 字符串去除空格

s1 = '   a b c  d e f  '
print(s1.strip(' '),len(s1.strip(' ')))
print(s1.lstrip(' '),len(s1.lstrip(' ')))
print(s1.rstrip(' '))


a b c  d e f 12
a b c  d e f   14
   a b c  d e f

In [24]:
# 字符串对齐

s1 = '12'
s2 = '2302'
print(s1.zfill(3))
print(s2.zfill(3))

print(s1.ljust(4))
print(s2.ljust(4))

print(s1.rjust(4))
print(s2.rjust(4))


012
2302
12  
2302
  12
2302

In [29]:
a='12345679012456'
print(a[8:4:-1])


0976

In [ ]: