实例化一个类但不调用它的 __init__ 方法 [英] Instantiate a class but don't call its __init__ method

查看:62
本文介绍了实例化一个类但不调用它的 __init__ 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以创建一个类的对象,但不要调用它的 __init__ 方法:

看下面的代码:

<预><代码>>>>类测试():def __init__(self):打印(这个类创建的对象")>>>一个=测试()此类创建的对象>>>

我想要一种方法来创建test() 类的对象,但不要打印创建的这个类的对象.

有什么办法吗?

更新:假设我已经实现了这个类并实例化了它的 20 个对象,我需要为它们所有的 __init__ 方法.现在我想实例化一些新对象,但我不想再调用它的 __init__ 方法.有什么办法吗?

解决方案

你可以直接调用 __new__ ,但我觉得你可能应该再考虑一下你的 __init__ 方法代替.

<预><代码>>>>A类(对象):... def __init__(self):...打印在__init__"...>>>a = A()在 __init__ 中>>>b = A.__new__(A)>>>类型(b)<类'__main__.A'>

I want to know if is there any way to make an object of a class, but don't call its __init__ method :

Look at the below code :

>>> class test():
    def __init__(self):
        print("an object created of this class")


>>> a=test()
an object created of this class
>>> 

I want a way to create an object of class test(), but don't print an object created of this class.

Is there any way?

Update: Assume that I implemented this class already and Instantiated 20 objects of it and I was need to its __init__ method for all of them. And now I want to instantiate some new objects, but I don't want to call its __init__ method any more. Is there any way?

解决方案

You can call __new__ directly, but I think you should probably think again about the design of your __init__ method instead.

>>> class A(object):
...   def __init__(self):
...     print "In __init__"
...
>>> a = A()
In __init__
>>> b = A.__new__(A)
>>> type(b)
<class '__main__.A'>

这篇关于实例化一个类但不调用它的 __init__ 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆