Chinaunix首页 | 论坛 | 博客
  • 博客访问: 443549
  • 博文数量: 97
  • 博客积分: 1552
  • 博客等级: 上尉
  • 技术积分: 1091
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-17 17:05
个人简介

专注于大规模运维场景运维工具解决方案。欢迎有这方面兴趣的朋友跟我联系。

文章分类

全部博文(97)

文章存档

2014年(12)

2013年(25)

2012年(60)

我的朋友

分类: Python/Ruby

2012-07-10 09:48:03

1、__call__关键字应用

点击(此处)折叠或打开

  1. >>> class g(object):
  2. ... def __init__(self,g):
  3. ... self.g = g
  4. ... def __call__(self,t):
  5. ... return (self.g * t ** 2)/2
  6. ...
  7. >>> e=g(9)
  8. >>> print e(2)
  9. 18
可以让一个对象成为一个可调用的函数.

2、面向对象基础理论
Python里面如何做到数据保护?
在C++里面定义private,在python里面是通过命名形式的方式进行处理的.私有属性以双下划线开头
私有方法也是以双下划线开头的
专用方法是以双下划线开头与双下划线结束.专用方法是对类的专用处理。比如__call__这样的专用方法

3、__getattr__与__getattribute__
class D(object):
    def __init__(self):
        self.default = 0.0
        self.test = 20
        self.test2 = 21
    def __getattribute__(self, name):
        try:
            if name == 'test':
                print ("__getattribute__ name = %s" % name)
                return self.test        #This will default call same function "__getattribute__", can fix by object
            else:
                print ("__getattribute__ name = %s" % name)
                return object.__getattribute__(self, name)
        except AttributeError:
            print "getattribute error"
            raise
    def __getattr__(self, name):
        print ("__getattr__ name = %s" % name)
        print ("self.default=%s" % self.default)
        return self.default
if __name__ == "__main__":
    d = D()
    #print d.test       #This will caused recurison error because it call the same function, your getattribute
    print d.test2
    print d.ts           #When "__getattribute__" raise error, it will call in "__getattr__".

4、面向对象总结
4.1 私有函数
在python里面没有private关键字,完全是依赖于它的名字的。
如果一个函数、类方法或属性以两个下划线开始,它是私有的。其他所有都是公有的。没有protected这个概念的。这一点要注意跟JAVA区别开来。
专有的方法:前后都是以两个下划线的比如__init__,__call__就是专有方法
抽象类:

点击(此处)折叠或打开

  1. class Employee:
  2.     def __init__(self, first, last):
  3.         if self.__class__ == Employee:
  4.             raise NotImplementedError, \
  5.                     "Cannot create object of class Employee"
  6.         self.firstName = first
  7.         self.lastName = last
  8.     
  9.     def __str__(self):
  10.         return "%s %s"%(self.firstName, self.lastName)

  11.     def _checkPositive(self, value):
  12.         if value < 0:
  13.             raise ValueError, \
  14.                     "Attribute value(%s) must be positive"%(value)
  15.         else:
  16.             return value
  17.     def earnings(self):
  18.         raise NotImplementedError, "Can not abstract method"

  19. class Boss(Employee):
  20.     def __init__(self, first, last, salary):
  21.         Employee.__init__(self, first, last)
  22.         self.weeklySalary = self._checkPositive(float(salary))
  23.     def earnings(self):
  24.         return self.weeklySalary
  25.     def __str__(self):
  26.         return "%17s:%s"%("Boss", Employee.__str__(self))

  27. employee = Boss("John", "Smith", 800.00)
  28. print employee, employee.earnings()
抽象类没有abstract定义,但是可以通过NotImplementedError类来模拟抽象类。
静态成员(类变量)
成员变量之前会有一个self,说明这个成员是属于类的实例。静态变量
class A:
    y = 2
print A.y 也可以
a = A()
print a.y  也是可以访问类的静态成员的
静态方法:
@staticmethod
实现如下:
class A:
    @staticmethod
    def prt():
       print "MyName is A"
A.prt()
获取对象的信息
对象的属性
self.__name__ 对象的名称
__class__     这是哪种类型的对象[抽象类的实现]
__doc__       对象知道些什么
__dict__      对象能做些什么
__bases__     对象的类继承自谁
__module__    它在哪一个模块中
自省函数
id()       返回对象唯一的标识符
repr()       返回对象的标准字符串表达式
type()       返回对象的类型
dir()       返回对象的属性名称列表
vars()       返回一个字典,它包含了对象存储于其__dict__中的属性及值
hasattr()     判断一个对象是否有一个特定的属性
getattr()     取得对象的属性
setattr()     赋值给对象的属性
delattr()     从一个对象中删除属性
callable()    测试对象的可调用性
issubclass()  判断一个类是否为另一个类的子类或孙类
isinstance()  判断一个对象是否是另一个给定类的实例
super()       返回相应的父类












阅读(1684) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~