介绍类首先看一个小例子

[root@wish1 413]# cat c.py 
class Dog():
    print "hello world"
    def buiik():
        print "wang,wang"
a=Dog()
a.buiik()

运行结果会出现报错

[root@wish1 413]# python c.py 
hello world
Traceback (most recent call last):
  File "c.py", line 6, in <module>
    a.buiik()
TypeError: buiik() takes no arguments (1 given)

改一下程序,再看一下变化

[root@wish1 413]# cat c.py 
class Dog():
    print "hello world"
    def buiik(self):
        print "wang,wang"
a=Dog()
a.buiik()
[root@wish1 413]# python c.py 
hello world
wang,wang

这就是self的作用:
类方法(也就是类的函数)与普通的函数的区别在于他们必须有一个额外的参数的名称,但是再调用这个类的时候,不为这个参数赋值。
定义类的私有属性】
在函数前面加两个__(下划线)
如果你想定义一个函数,不想让外部看见,在类中定义,

root@wish1 413]# cat c.py 
class Dog():
    print "hello world"
    def buiik(self):
        print "wang,wang"
    def __auth():
        print "can not be see outside" ##定义类的私有属性
    __auth()
a=Dog()
a.buiik()

[root@wish1 413]# python c.py 
hello world
can not be see outside
wang,wang

【解构器】
在类结束调用的时候自动执行

[root@wish1 413]# cat c.py 
class Dog():
    print "hello world"
    def buiik(self):
        print "wang,wang"
    def __del__(self):
        print "bye bye"
a=Dog()
a.buiik()

运行:

[root@wish1 413]# python c.py 
hello world
wang,wang
bye bye

可以看到在程序中并没有调用__del__函数,在类调用的时候,最后输出执行了__del__,这就是类的解构器

转载于:https://www.cnblogs.com/hanfei-1005/p/5704252.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值