- 浏览: 247193 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (127)
- vim (3)
- python (44)
- pymysql (1)
- mysql (9)
- macvim (1)
- erlang (3)
- twisted (0)
- tornado (5)
- django (7)
- postgresql (5)
- sql (1)
- java (7)
- tech (4)
- cache (1)
- lifestyle (3)
- html (1)
- ubuntu (2)
- rabbitmq (1)
- algorithm (8)
- Linux (4)
- Pythonista (1)
- thread (1)
- sort (6)
- 设计模式 (1)
- search (1)
- Unix (6)
- Socket (3)
- C (2)
- web (1)
- gc (1)
- php (10)
- macos (1)
最新评论
-
2057:
这个程序有bug。
查找算法学习之二分查找(Python版本)——BinarySearch -
dotjar:
NB
一个Python程序员的进化[转]
Contains:
一、__init__通过此方法我们可以顶一个对象的初始操作。
但是当我新建一个类的实例的时候,__init__并不是第一个被调用的,实际上,还有一个叫做__new__的方法,来构造这个实例。然后在给开始创建的初始化函数传递参数。
二、__new__
__new__方法相当不常用,但是它有自己的特性,特别是当继承一个不可变的类型比如一个tuple或者string.
Q:可是什么时候使用__new__?
难道是这个吗?特别是当继承一个不可变的类型比如一个tuple或者string.
object.__new__(cls[, …])
Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).
Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...])with appropriate arguments and then modifying the newly-created instance as necessary before returning it
If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
三、__call__
这个方法可以让类的实例的行为表现的像函数一样,你可以调用他们,讲一个函数当做一个参数传到另外一个函数中等等。
result:
before __call__ (2, 3)
after __call__ (4, 5)
参考资料:
http://docs.python.org/2/reference/datamodel.html
http://stackoverflow.com/questions/8106900/new-and-init-in-python
http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
http://www.wingide.com/psupport/python-manual/2.4/ref/customization.html
http://stackoverflow.com/questions/12971641/need-to-understand-the-flow-of-init-new-and-call?lq=1
http://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/a-guide-to-pythons-magic-methods.html
- __new__: 创建对象时调用,返回当前对象的一个实例
- __init__:创建完成对象后调用,对当前对象的实例的一些初始化,无返回值
- __call__:
一、__init__通过此方法我们可以顶一个对象的初始操作。
但是当我新建一个类的实例的时候,__init__并不是第一个被调用的,实际上,还有一个叫做__new__的方法,来构造这个实例。然后在给开始创建的初始化函数传递参数。
二、__new__
@staticmethod # known case of __new__ def __new__(cls, *more): # known special case of object.__new__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass
__new__方法相当不常用,但是它有自己的特性,特别是当继承一个不可变的类型比如一个tuple或者string.
Q:可是什么时候使用__new__?
难道是这个吗?特别是当继承一个不可变的类型比如一个tuple或者string.
引用
object.__new__(cls[, …])
Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).
Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...])with appropriate arguments and then modifying the newly-created instance as necessary before returning it
If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
三、__call__
引用
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).
这个方法可以让类的实例的行为表现的像函数一样,你可以调用他们,讲一个函数当做一个参数传到另外一个函数中等等。
class Entity: def __init__(self,x,y): self.x = x self.y = y def __call__(self, x, y): self.x = x self.y = y entity = Entity(2,3) print 'before __call__',(entity.x,entity.y) entity.__call__(4,5) print 'after __call__',(entity.x,entity.y)
result:
before __call__ (2, 3)
after __call__ (4, 5)
参考资料:
http://docs.python.org/2/reference/datamodel.html
http://stackoverflow.com/questions/8106900/new-and-init-in-python
http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
http://www.wingide.com/psupport/python-manual/2.4/ref/customization.html
http://stackoverflow.com/questions/12971641/need-to-understand-the-flow-of-init-new-and-call?lq=1
http://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/a-guide-to-pythons-magic-methods.html
发表评论
-
macos 10.9.2 clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command
2014-03-25 19:13 1760方法总是有的,当然需要你去寻找。 当然如果花费太多的时间在一件 ... -
PostgreSQL psycopg2:IndexError: tuple index out of range
2014-01-09 17:04 2231Postgresql psycopg2使用like查询的时候 ... -
Python 迭代器和生成器
2013-10-15 23:09 2850迭代器 迭代器只不过是一个实现迭代器协议的容器对象。它基于两个 ... -
Python时间模块
2013-10-15 23:03 3469time模块 时间模块中最常用的一个函数就是获取当前时间的函数 ... -
Python装饰器
2013-10-15 22:59 1569编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一 ... -
python list
2013-10-15 22:56 1254简单总结以及整理如下: >>> dir( ... -
Python Excel
2013-09-10 17:21 976安装lib easy_install xlrd def ... -
排序算法学习(python版本)之堆排序(HeapSort)
2013-07-01 22:54 1997Contains: 堆排序以及堆排序的应用 堆排序(Heaps ... -
python range xrange
2013-06-25 23:30 1149引用Help on built-in function ran ... -
python class
2013-06-25 00:54 1829引用类是创建新对象类 ... -
AttributeError: 'module' object has no attribute 'SendCloud'
2013-06-05 11:46 7083网上查了下 意思是说你命名的文件名不能和lib重名,这样会导 ... -
python string
2013-05-07 23:44 2198如果这就是字符串,这本来就是字符串 首先看下字符串的方法 ... -
Python property
2013-03-29 19:56 0由于之前有总结过,可以参考http://2057.iteye. ... -
python tips
2013-03-28 23:57 8831、enum #!/usr/bin/env python ... -
python decorators
2013-03-28 23:36 1365Contains: 1、decorators 2、funct ... -
python closures
2013-03-28 22:09 1190Closure:如果在一个内部函数里,对在外部作用域(但不是在 ... -
Python map、filter,reduce介绍
2013-03-28 22:02 13091、filter(function,iterable) 引用C ... -
Python socket简介
2013-03-25 23:42 2169自豪地使用dir和help. Python 2.7.2 ( ... -
Tornado ioloop源码简析
2013-03-21 00:18 2850#!/usr/bin/env python #-*-en ... -
Tornado httpserver 源码简析
2013-03-17 01:49 1790整个流程就是创建一个socket socket.socket ...
相关推荐
在Python的面向对象编程中,`__init__`、`__new__`和`__call__`是三个非常重要的特殊方法,它们各自扮演着特定的角色。这篇文章将详细讲解这三个方法的功能、用途以及如何正确使用。 首先,`__init__`方法是对象的...
__call__ : 对象可call,注意不是类,是对象。 先有创建,才有初始化。即先__new__,而后__init__。 上面说的不好理解,看例子。 1.对于__new__ class Bar(object): pass class Foo(object): def __new__(cls, ...
注意,这里的第一个参数是self即对象本身【注意和new的区别】3.__call__(self, *args, **kwargs) 如果类实现了这个方法,相当于把这个类型的对象当作函数来使用,相当于 重载了括号运算符 看具体的例子:复制代码...
工厂函数是一种创建对象的函数,而不是直接使用`new`或`__call__`。在Python中,工厂函数可以简化复杂对象的创建,尤其是在处理继承层次结构时。 例如,我们可以创建一个扑克牌游戏,包含AceCard、NumberCard和...
在这个例子中,`call_method`函数接受一个对象作为参数,并调用它的`method`方法。尽管`obj1`和`obj2`来自不同的类,但它们都可以响应`method`调用,这就是多态性。 四、访问控制 1. **访问修饰符**:Python没有...
- **`__call__` 方法**:允许将实例当作函数来调用,即实现类似函数的功能。 ```python class CallableClass: def __call__(self, *args, **kwargs): print("Called with arguments:", args, "and keyword ...
- **`__call__`**:使对象可以像函数一样被调用。 #### 使用示例 假设我们需要定义一个简单的文件操作类`FileObject`,该类可以自动打开和关闭文件: ```python from os.path import join class FileObject: '...
在这个例子中,我们定义了一个名为 `Singleton` 的元类,并重写了 `__call__` 方法。当使用这个元类定义的类被实例化时,`__call__` 方法会被调用,从而返回单例实例。 #### 使用 `__new__` 方法 另一种实现单例...
cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class MySingletonGUI(metaclass=SingletonMeta): def __init__(self): pass ``` 在“python单例模式.txt”文件中,...
- **格式**:`def __call__(self, *args, **kwargs):` - **示例**: ```python class MyClass: def __call__(self, x, y): return x + y ``` #### 7. `__nonzero__` (Python 2) / `__bool__` (Python 3) - **...
conn.call_proc(sql) return xxx exc1('127.0.0.1', 3306, 'db1', 'utf8', 'select * from tb1;') exc2('127.0.0.1', 3306, 'db1', 'utf8', '存储过程的名字') ``` **优化后的代码:** ```python class DB: def...
内容:面向对象 面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了。...魔法函数: 3.1init()构造函数、__str__()、__call__()、__new__()
如果需要避免多次初始化,可以在`__new__`或元类的`__call__`方法中添加条件逻辑,比如使用一个标志来记录是否已经初始化过。但这通常不是必需的,因为通常初始化不会带来副作用,且单例模式主要关注的是对象的唯一...
cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs) return cls._instances[cls] class Singleton(metaclass=SingletonMeta): def __init__(self): pass ``` 每种实现单例模式的方法...
print(dir(my_function)) # 输出:['__call__', '__class__', ...] print(hasattr(my_function, '__call__')) # 输出:True print(getattr(my_function, '__name__')) # 输出:my_function ``` #### 6. 字典推导式 ...
通过创建一个元类Singleton,重写`__init__`和`__call__`方法来控制实例化过程,确保类的实例只有一个。例如: ```python class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if ...