• 介绍类首先看一个小例子

    [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__,这就是类的解构器

  • 相关阅读:
    Binomial Coeffcients(山东省第二届省赛G题)
    合法的C标示符(判断是否是数字或字母)
    HDU2544最短路问题Floydwarshall Algorithm做法
    简单N的阶乘
    手动实现类的属性
    基本语法基本的数据类型
    UITableViewCell的背景
    基本语法类
    UITableView专题
    单击视图空白处隐藏IPhone键盘
  • 原文地址:https://www.cnblogs.com/hanfei-1005/p/5704252.html
Copyright © 2020-2023  润新知