|  | 
 
| 
>>> class Turtle:
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  ...         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 参数传递的信息。
 >>>
 | 
 |