13_Python 类的属性和方法

Python 类

  • 类的定义
    • 类的方法至少有一个参数self
class MyClass(object):
    def fun(self):
	    print '类的方法'
  • 类的实例化 --> 创建对象
obj = MyClass
  • 类的属性

    • 公有属性: 类内外都能调用的属性
    • 私有属性:不能在类外以及被类以外的函数调用,私有属性定义方法:以双下划线开始的成员变量就是私有属性
    • 内置属性:系统在定义类的时候默认添加的,由前后双下划线构成,
      • dict:类的属性(包含一个字典,由类的数据属性组成)
      • doc:类的文档字符串
      • name:类名
      • module:类定义所在的模块
  • 类的方法:类的方法定义跟函数的定义一样,但是需要self作为第一个参数

    • 公有方法:在类中类外都能调用的方法
    • 私有方法:不能被类的外部调用,私有方法定义:方法前面加上双下划线,
  • 类方法:被classmethod()函数处理过,才能被类所调用

    	In [8]: class Testing(object):
    	...:     def test(self):
    	...:         print('hello test')
    	...:     def test2(self):
    	...:         print('hello test2')
    	...:     pt = classmethod(test)
    	...:     
    
    	In [9]: Testing.pt()
    	hello test
    
    	In [10]: Testing.test()         ##是不能直接通过类调用类方法的,
    	-------------------------------------------------------------------
    	TypeError                         Traceback (most recent call last)
    	<ipython-input-10-372b771144d0> in <module>()
    	----> 1 Testing.test()
    
    	TypeError: unbound method test() must be called with Testing 
    	instance as first argument (got nothing instead)
    
    	In [11]: Testing.test2()
    	-------------------------------------------------------------------
    	TypeError                        Traceback (most recent call last)
    	<ipython-input-11-f17045d44574> in <module>()
    	----> 1 Testing.test2()
    
    	TypeError: unbound method test2() must be called with Testing 
    	instance as first argument (got nothing instead)
    
  • 静态方法:相当于“全局函数”,可以被类直接调用,可以被所有实例化对象共享,通过staticmethod()定义,静态方法没有“self”参数。

转载于:https://my.oschina.net/u/4023720/blog/2980656

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值