鱼C论坛

 找回密码
 立即注册
查看: 1532|回复: 1

[学习笔记] 类和对象-Ⅰ

[复制链接]
发表于 2023-3-17 20:13:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
>>> class Turtle:
...         head = 1
...         eyes = 2
...         legs = 4
...         shell = True
...         def crawl(self):
...                 print("抓子crawl")
...         def run(self):
...                 print("赶紧跑")
...         def bite(self):
...                 print("会咬人")
...         def eat(self):
...                 print("会吃饭")
...         def sleep(self):
...                 print("Zzzz...")
...
>>> # 所谓的属性,就是写在类里面的变量,方法就是写在类里面的函数
>>> # t1 就是一个 Turtle 类的对象,也叫实例对象(instance object),它就拥有了这个类所定义的属性和方法:
>>> t1 = Turtle()
>>> t1.head
1
>>> t1.eyes
2
>>> t1.crawl()
抓子crawl
>>> t1.sleep
<bound method Turtle.sleep of <__main__.Turtle object at 0x016BF490>>
>>> t1.sleep()
Zzzz...
>>> t2 = Turtle()
>>> t2.shell
True
>>> t2.legs
4
>>> t2.eat()
会吃饭
>>> t2.legs = 3
>>> t2.legs
3
>>> t1.legs
4

>>> # 也可以动态的创建一个属性,这跟在字典中添加一个新的键值对一样:
>>> t1.mouth = 1
>>> t1.mouth
1

>>> dir(t1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bite', 'crawl', 'eat', 'eyes', 'head', 'legs', 'mouth', 'run', 'shell', 'sleep']
>>> dir(t2)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bite', 'crawl', 'eat', 'eyes', 'head', 'legs', 'run', 'shell', 'sleep']

>>> # self 是什么?
>>> class C:
...         def get_self(self):
...                 print(self)
...
>>> c = C()
>>> c.get_self()
<__main__.C object at 0x021FE358>
>>> # 这就是类 C 的实例对象小 c
>>> c
<__main__.C object at 0x021FE358>
>>> # 同一个类可以生成无数多个对象,那么当我们在调用类里面的一个方法的时候,Python 如何知道到底是哪个对象在调用呢?
>>> # 没错,就是通过这个 self 参数传递的信息。
>>>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-3-29 13:09:13 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-8 02:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表