python面向对象基础

定义类

  • 经典类或旧式类(不由任意内置类型派生出的类,称之为经典类)。
class 类名:
    """说明文档"""
    代码
    ......
  • 拓展2:新式类
class 类名(object):
    """说明文档"""
  代码

注意:类名要满足标识符命名规则,同时遵循大驼峰命名习惯

示例

class Washer():
    def wash(self):
        print('我会洗衣服')

创建对象

对象又名实例。

  • 语法
对象名 = 类名()
  • 体验
# 创建对象
haier1 = Washer()
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)

# haier对象调用实例方法
haier1.wash()

注意:创建对象的过程也叫实例化对象。

self

self指的是调用该函数的对象。

# 1. 定义类
class Washer():
    def wash(self):
        print('我会洗衣服')
        # <__main__.Washer object at 0x0000024BA2B34240>
        print(self)

# 2. 创建对象
haier1 = Washer()
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)
# haier1对象调用实例方法
haier1.wash()

haier2 = Washer()
# <__main__.Washer object at 0x0000022005857EF0>
print(haier2)

注意:打印对象和self得到的结果是一致的,都是当前对象的内存中存储地址。

添加和获取对象属性

python 是动态语言 可以随时绑定新的属性和方法。对象属性既可以在类外面添加和获取,也能在类里面添加和获取。

类外面添加对象属性

  • 语法
对象名.属性名 = 值

类外面获取对象属性

  • 语法
对象名.属性名

类里面获取对象属性

  • 语法
self.属性名

完整示例

#定义类
class Hero(object): 
    def __init__(self, name, init_health=100, init_attack=10, alive=True):
        # 构造函数/初始化方法 在创建对象时候执行
        self.name = name  # 为对象绑定属性
        self.health = init_health
        self.attack = init_attack
        self.alive = True
        
        self.birth()

    def attack_enemy(self, enemy):
        # 对象的方法 用本类创建的所有对象都有这个方法
        enemy.health -= self.attack
        if enemy.health <= 0:
            enemy.alive = False 
            enemy.health = 0
            print(f'{enemy.name} 死亡')

    def upgrade(self):
        self.attack *= 1.1
        self.health *= 1.1

    def birth(self):
        print(f'我,{self.name},出生了!')
# 实例化对象
hero1 = Hero('亚瑟', 1000, 100)
hero2 = Hero('安琪拉', 500, 500)
#
我,亚瑟,出生了!
我,安琪拉,出生了!
# 访问属性
print(f'亚瑟的生命值:{hero1.health} 亚瑟的攻击力:{hero1.attack}')
print(f'安琪拉的生命值:{hero2.health} 安琪拉的攻击力:{hero2.attack}')
##
亚瑟的生命值:1000 亚瑟的攻击力:100
安琪拉的生命值:500 安琪拉的攻击力:500
# 调用方法
hero1.attack_enemy(hero2)
print(f'亚瑟的生命值:{hero1.health} 亚瑟的攻击力:{hero1.attack}')
print(f'安琪拉的生命值:{hero2.health} 安琪拉的攻击力:{hero2.attack}')
##
亚瑟的生命值:1000 亚瑟的攻击力:100
安琪拉的生命值:400 安琪拉的攻击力:500
#没有定义的属性,类直接访问,会报错
hero1.height
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

/tmp/ipykernel_104/859449670.py in <module>
----> 1 hero1.height

AttributeError: 'Hero' object has no attribute 'height'
# python 是动态语言 可以随时绑定新的属性和方法
hero1.height=60
# print(hero1.height)
print(hero2.height)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

/tmp/ipykernel_104/509620292.py in <module>
      2 hero1.height=60
      3 # print(hero1.height)
----> 4 print(hero2.height)

AttributeError: 'Hero' object has no attribute 'height'

## 动态绑定方法
hero1.show = print
hero1.show('hello')

posted @ 2021-12-15 11:04  莳苡  阅读(31)  评论(0)    收藏  举报