类/对象/封装

对象=属性+方法

需要先创建一个类(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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值