对象=属性+方法
需要先创建一个类(class)
class Turtle:
head = 1
eyes = 2
legs = 4
shell = True
def crawl(self):
print("人们总抱怨我动作慢吞吞得,殊不知如不积跬步无以至千里的道理。")
def run(self):
print("虽然我行动的很慢,但如果遇到危险,还是会夺命狂奔T_T")
def bite(self):
print("人善被人欺,鬼善被人骑,我可是会咬人的!")
def eat(self):
print("谁知盘中餐粒粒皆辛苦,吃得好,不如吃的饱~")
def sleep(self):
print("Zzzz....")
t1 = Turtle() """t1即为创建的对象,拥有Turtle的属性值"""
t1.head
1
t1.legs
4
t1.crawl
<bound method Turtle.crawl of <__main__.Turtle object at 0x0000013BE6D46650>>
t1.crawl()
人们总抱怨我动作慢吞吞得,殊不知如不积跬步无以至千里的道理。
t1.bite()
人善被人欺,鬼善被人骑,我可是会咬人的!
t1.sleep()
Zzzz....
t2 = Turtle()
t2.legs=3
t2.legs
3
t1.legs
4
t1.mouth=1 """t1可以增加属性值,而不影响其他的对象"""
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是什么?若无self的话,报以下错误
class C :
def hello():
print("你好")
c=C()
c.hello()
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
c.hello()
TypeError: C.hello() takes 0 positional arguments but 1 was given
class C :
def get_self(self):
print(self)
c = C()
c.get_self()
<__main__.C object at 0x0000013BE6D46CB0> """由此可见self是实例化对象的本身"""
c
<__main__.C object at 0x0000013BE6D46CB0>