这部分内容写了好几天了,但是感觉还是不是太明白,因此也没有写的太明白,先发这些,期待高手答疑解惑
这里说的是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,现在举例说明:
-
from os.path import join
-
-
class FileObject:
-
'''Wrapper for file objects to make sure the file gets closed on deletion.'''
-
-
def __init__(self, filepath='~', filename='sample.txt'):
-
# open a file filename in filepath in read and write mode
-
self.file = open(join(filepath, filename), 'r+')
-
-
def __del__(self):
-
self.file.close()
-
del self.file
说它是magic函数是因为,它是被python自动调用,无需显示的调用,下面三个magic函数在类中有两个比较常见,其中第一个为类成员方法(class method),在继续之前,补充一下,类成员方法,与类静态方法的区别,
-
class NewClass():
-
''' demo of class attribute about static method & class method'''
-
# number of class instance
-
count = 0
-
def __init__(self):
-
self.name='kinfinger'
-
NewClass.count =+1
-
def smethod():
-
print 'this is static method of class'
-
def cmethod(cls):
-
print 'this is a class method of class',cls.count
-
sm=staticmethod(smethod)
-
cm=classmethod(cmethod)
-
def main():
-
print 'somth about access different'
-
NewClass.sm()
-
NewClass.cm()
-
nc=NewClass()
-
print 'something about instacne '
-
nc.sm()
-
nc.cm()
-
if __name__ == '__main__':
-
main()
可以看到,静态方法和类方法既可以使用类调用,也可以使用instance调用,但是使用静态方法与类方法之前
要进行适当的装饰,即将二者装入函数staticmethod,classmethod,二者的详细介绍如下:
-
help> classmethod
-
Help on class classmethod in module __builtin__:
-
-
class classmethod(object)
-
| classmethod(function) -> method
-
|
-
| Convert a function to be a class method.
-
|
-
| A class method receives the class as implicit first argument,
-
| just like an instance method receives the instance.
-
| To declare a class method, use this idiom:
-
|
-
| class C:
-
| def f(cls, arg1, arg2, ...): ...
-
| f = classmethod(f)
-
|
-
| It can be called either on the class (e.g. C.f()) or on an instance
-
| (e.g. C().f()). The instance is ignored except for its class.
-
| If a class method is called for a derived class, the derived class
-
| object is passed as the implied first argument.
-
|
-
| Class methods are different than C++ or Java static methods.
-
| If you want those, see the staticmethod builtin.
-
help> staticmethod
-
Help on class staticmethod in module __builtin__:
-
-
class staticmethod(object)
-
| staticmethod(function) -> method
-
|
-
| Convert a function to be a static method.
-
|
-
| A static method does not receive an implicit first argument.
-
| To declare a static method, use this idiom:
-
|
-
| class C:
-
| def f(arg1, arg2, ...): ...
-
| f = staticmethod(f)
-
|
-
| It can be called either on the class (e.g. C.f()) or on an instance
-
| (e.g. C().f()). The instance is ignored except for its class.
-
|
-
| Static methods in Python are similar to those found in Java or C++.
在python新的特性中,又继续引入了decorator来简化操作,这里不做讨论。
-
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)
-
__new__(cls, [...)
-
__init__(self, [...)
-
__del__(self)
在中指出
__new__ 是一个staticmethod,它返回一个对象实例 同上面的介绍有点不符,,上面的语法指出它是一个clasmethod,那么该方法到底是什么呢?
动手测一把(思路不清晰,后续补上)
-
__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.
-
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) |