python的类和对象

1.类的三要素
在这里插入图片描述
2.类的内置函数
(1)dir(函数名) 可以得到含指数中的内置方法或属性
在这里插入图片描述
3.定义类和对象

class Text:
	def 方法1(self):
		pass
	def 方法2(self):
		pass
		
对象变量=类名()

4.对象名.属性名=内容 可以增加属性(在类外面定义属性不推荐)

class Cat:
	def eat(self):
		print(%s爱吃鱼%self.name)
		
Tom=Cat()
Tom.name="Tom"
Tom.eat()

5.初始化方法
(1)(定义类的属性 def __ init__(self))

class Cat:
    # 初始化属性
    def __init__(self):
        self.name = "Tom"
        self.gender = True
        

tom = Cat()

如果想属性值不被限死就用形参

class Cat:
    # 初始化属性
    def __init__(self, new_name):
        self.name = new_name
        self.gender = True


tom = Cat("Tom")

(2)初始化方法(__ del __(self))

class Cat:
    # 初始化属性
    def __init__(self, new_name):
        self.name = new_name
        print("%s来了" % self.name)

    def __del__(self):
        print("%s走了" % self.name)


tom = Cat("Tom")
del tom

(3)初始化方法(__ str __(self))

class Cat:
    # 初始化属性
    def __init__(self, new_name):
        self.name = new_name
        print("%s来了" % self.name)

    def __del__(self):
        print("%s走了" % self.name)

    def __str__(self):
    	#一定要返回一个字符串
        return "我是%s小猫" % self.name


tom = Cat("Tom")

print(tom)

输出结果
在这里插入图片描述

6.演练:枪对象

class Gun:
    def __init__(self, module):
        self.name = module
        self.bullet_count = 0

    def add_bullet(self, bullet):
        self.bullet_count = bullet

    def shot(self):
        if self.bullet_count <=0:
            print ("%s没有子弹了"%self.name)
        else:
            self.bullet_count -= 1
            print("%s 突突突...[%d]" %(self.name, self.bullet_count))


ak47=Gun("AK47")
ak47.add_bullet(50)
ak47.shot()

运行结果
在这里插入图片描述
士兵对象:

class Gun:
    def __init__(self, module):
        self.name = module
        self.bullet_count = 0

    def add_bullet(self, bullet):
        self.bullet_count = bullet

    def shot(self):
        if self.bullet_count <=0:
            print ("%s没有子弹了"%self.name)
        else:
            self.bullet_count -= 1
            print("%s 突突突...[%d]" %(self.name, self.bullet_count))

class Soldier:
    def __init__(self, name):
        self.name = name
        #新兵没有枪
        self.gun = None

    def fire(self):
        # 判断有没有枪
        if self.gun == None:
            print("%s没有枪" % self.name)
            return
        else:
            print("%s冲啊"%self.name)
            self.gun.add_bullet(50)
            self.gun.shot()



ak47 = Gun("AK47")
xusanduo = Soldier("许三多")
xusanduo.gun = ak47
xusanduo.fire()

7.身份运算符is / is not 比较地址 == 比较值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值