Python重载学习手记

来源:互联网 发布:oracle 数据挖掘工具 编辑:程序博客网 时间:2024/04/30 22:22

今天学习了一下Python的操作符重载,总结了几点比较神奇的东东:

------------------------------------------------------------------------------------------------------------

关于iter:
Technically, iteration contexts work by calling the iter built-in function to try to
find an _ _iter_ _ method, which is expected to return an iterator object. If it’s

provided,Python then repeatedly calls this iterator object’s next method to produce
items until a StopIteration exception is raised. If no such _ _iter_ _ method is found,
Python falls back on the _ _getitem_ _ scheme, and repeatedly indexes by offsets as
before, until an IndexError exception is raised.
所以为了使用iter,我们必须重载__iter__,然后再定义一个next方法,例子如下:
class Squares:
 def _ _init_ _(self, start, stop): # Save state when created
  self.value = start - 1
  self.stop = stop
 def _ _iter_ _(self): # Get iterator object on iter( )
  return self
 def next(self): # Return a square on each iteration
  if self.value == self.stop:
   raise StopIteration
  self.value += 1
  return self.value ** 2

------------------------------------------------------------------------------------------------------------

 

------------------------------------------------------------------------------------------------------------

利用__setattr__的时候,自己赋值不可以使用self.name = value,因为这个语句也是用了__setattr__

,这样重复使用,出错。要使用self.__dict__['name'] = value

------------------------------------------------------------------------------------------------------------

 

------------------------------------------------------------------------------------------------------------

利用__getattr__建立“私有”成员变量:
利用重载的__setattr__在每次取之前判断一下私有成员名字当中有没有,来实现私有,代码如下(取自

Learning Python)
class PrivateExc(Exception): pass

class Privacy:
    def __setattr__(self,attrname, value):
        if attrname in self.privates:
            raise PrivateExc(attrname, self)
        else:
            self.__dict__[attrname] = value
class Test1(Privacy):
    privates = ['age']

class Test2(Privacy):
    privates = ['name', 'pay']
    def __init__(self):
        self.__dict__['name'] = 'Tom'

x = Test1()
y = Test2()

x.name = 'Bob'
y.name = 'Sue' #This will raise the exception!!!

y.age = 30
x.age = 40 #And so will this!

 

------------------------------------------------------------------------------------------------------------
先找__str__再找__repr__,因此多用__repr__
在交互界面中输入x,调用的是repr(x),而输入print x,调用的是str(x)

------------------------------------------------------------------------------------------------------------

 

 

------------------------------------------------------------------------------------------------------------

__getitem__用来下标运算

------------------------------------------------------------------------------------------------------------

 

原创粉丝点击