类
介绍类首先看一个小例子
[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__,这就是类的解构器