Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1792020
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2013-05-05 21:43:46

      这部分内容写了好几天了,但是感觉还是不是太明白,因此也没有写的太明白,先发这些,期待高手答疑解惑
     这里说的是Method,而不是Function,其实严格的说这二者并没有严格的界限,但是在Python中,二者还是略有不同,method更多的是针对类中的方法。看到这里,你就知道我想介绍的内容就是 Method,而且是 Magic Method,那么什么是Magic Method?
其实定义很简单:就是类似__Method__的函数,是不是很眼熟?学习Class时,你需要定义的第一个函数就是这样的,
What are magic methods? They're everything in object-oriented Python.
 They're special methods that you can define to add "magic" to your classes. 
They're always surrounded by double underscore
那么说这样的函数是Magic Method?那么它到底神奇在哪里呢?通过定义,我们知道,它们主要在面向对象的Python中。它们的存在使得你的class可以具有Magic,现在举例说明:

点击(此处)折叠或打开

  1. from os.path import join

  2. class FileObject:
  3.     '''Wrapper for file objects to make sure the file gets closed on deletion.'''

  4.     def __init__(self, filepath='~', filename='sample.txt'):
  5.         # open a file filename in filepath in read and write mode
  6.         self.file = open(join(filepath, filename), 'r+')

  7.     def __del__(self):
  8.         self.file.close()
  9.         del self.file
说它是magic函数是因为,它是被python自动调用,无需显示的调用,下面三个magic函数在类中有两个比较常见,其中第一个为类成员方法(class method),在继续之前,补充一下,类成员方法,与类静态方法的区别,

点击(此处)折叠或打开

  1. class NewClass():
  2.     ''' demo of class attribute about static method & class method'''
  3.     # number of class instance
  4.     count = 0
  5.     def __init__(self):
  6.         self.name='kinfinger'
  7.         NewClass.count =+1
  8.     def smethod():
  9.         print 'this is static method of class'
  10.     def cmethod(cls):
  11.         print 'this is a class method of class',cls.count
  12.     sm=staticmethod(smethod)
  13.     cm=classmethod(cmethod)
  14. def main():
  15.     print 'somth about access different'
  16.     NewClass.sm()
  17.     NewClass.cm()
  18.     nc=NewClass()
  19.     print 'something about instacne '
  20.     nc.sm()
  21.     nc.cm()
  22. if __name__ == '__main__':
  23.     main()
可以看到,静态方法和类方法既可以使用类调用,也可以使用instance调用,但是使用静态方法与类方法之前
要进行适当的装饰,即将二者装入函数staticmethod,classmethod,二者的详细介绍如下:

点击(此处)折叠或打开

  1. help> classmethod
  2. Help on class classmethod in module __builtin__:

  3. class classmethod(object)
  4.  | classmethod(function) -> method
  5.  |
  6.  | Convert a function to be a class method.
  7.  |
  8.  | A class method receives the class as implicit first argument,
  9.  | just like an instance method receives the instance.
  10.  | To declare a class method, use this idiom:
  11.  |
  12.  | class C:
  13.  | def f(cls, arg1, arg2, ...): ...
  14.  | f = classmethod(f)
  15.  |
  16.  | It can be called either on the class (e.g. C.f()) or on an instance
  17.  | (e.g. C().f()). The instance is ignored except for its class.
  18.  | If a class method is called for a derived class, the derived class
  19.  | object is passed as the implied first argument.
  20.  |
  21.  | Class methods are different than C++ or Java static methods.
  22.  | If you want those, see the staticmethod builtin.

点击(此处)折叠或打开

  1. help> staticmethod
  2. Help on class staticmethod in module __builtin__:

  3. class staticmethod(object)
  4.  | staticmethod(function) -> method
  5.  |
  6.  | Convert a function to be a static method.
  7.  |
  8.  | A static method does not receive an implicit first argument.
  9.  | To declare a static method, use this idiom:
  10.  |
  11.  | class C:
  12.  | def f(arg1, arg2, ...): ...
  13.  | f = staticmethod(f)
  14.  |
  15.  | It can be called either on the class (e.g. C.f()) or on an instance
  16.  | (e.g. C().f()). The instance is ignored except for its class.
  17.  |
  18.  | Static methods in Python are similar to those found in Java or C++.
 在python新的特性中,又继续引入了decorator来简化操作,这里不做讨论。

点击(此处)折叠或打开

  1. Everyone knows the most basic magic method, __init__. It's the way that we can define the initialization behavior of an object. However, when I call x = SomeClass(), __init__ is not the first thing to get called. Actually, it's a method called __new__, which actually creates the instance, then passes any arguments at creation on to the initializer. At the other end of the object's lifespan, there's __del__. Let
两个上面例子中用到的函数,这里需要注意的函数 __new__,即类方法(classmethod)

点击(此处)折叠或打开

  1. __new__(cls, [...)
  2. __init__(self, [...)
  3. __del__(self)
        在中指出 __new__ 是一个staticmethod,它返回一个对象实例    同上面的介绍有点不符,,上面的语法指出它是一个clasmethod,那么该方法到底是什么呢?
动手测一把(思路不清晰,后续补上)


点击(此处)折叠或打

  1. __new__ is the first method to get called in an object's instantiation. It takes the class, then any other arguments that it will pass along to __init__. __new__ is used fairly rarely, but it does have its purposes, particularly when subclassing an immutable type like a tuple or a string. 
  1. The initializer for the class. It gets passed whatever the primary constructor was called with (so, for example, if we called x = SomeClass(10, 'foo'), __init__ would get passed 10 and 'foo' as arguments. __init__ is almost universally used in Python class definitions.
阅读(1365) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~