简单地说我想得到一个派生类对象,但是我想使用_existing_Base'的而不是允许创建Base实例的 _automatic_。例如,然后将其用作Derived'的实例。 元类会解决这个问题吗? 解决方案 Sridhar R写道: 考虑下面的代码, 类Base(对象):传递 class Derived(object): 我想应该是 class Derived(Base): def __new __(cls, * args,** kwds):#some_factory返回Base的实例#我必须从这个实例派生! inst = some_factory()#this返回Base $ b的实例$ b #使用蛮力: inst .__ class__ =派生 无保证,但以上似乎都有效。 return inst#糟糕!这不是派生的实例 def __init __(自我):#这不会被称为__new__返回Base'的实例传递 constrait有一些工厂函数可以创建一个Base类的实例。所以我_不能叫'Base .__ init __(self)"在 Derived .__ init__ func中,因为它们将是_two_实例(一个由Derived .__ init__创建,另一个由工厂函数创建) as some_factory( )返回一个已经初始化的Base实例,那里 应该不需要再从Derived里面调用它.__ init __() 我想得到一个派生类对象,但不是允许创建Base实例,我想使用_existing_Base'的实例,然后将其用作Derived'的实例。 将元类解决了这个问题? 我认为元类只能解决元问题... 怀疑你的, Peter " Sridhar R" < SR ************* @ yahoo.com>在消息中写道 news:93 ************************** @ posting.google.c om ... 考虑下面的代码, 类Base(对象):传递 类派生(对象): def __new __(cls,* args,** kwds):#some_factory返回Base的实例#我必须从这个实例派生出来! inst = some_factory( )#this返回Base的实例 return inst #Oops!这不是衍生的实例 def __init __(自我):#这不会被称为__new__返回Base'的实例传递 __new__可以返回它所喜欢的任何类的实例。 它不仅限于返回类的实例它 恰好是,但也不限于返回一个新的 创建的实例。它可以在不使用__init__方法的情况下完成整个 构建工作。 但是,我不认为这是最好的解决方案。如果 你的工厂将返回几个不同类别的实例,我认为它最好是一个明确的 工厂方法或函数,而不是在类构造函数中发生的奇怪的事情。我宁愿不必处理处理类构造函数传递给我的程序 除了我正在调用的类之外​​的类实例。 如果你想做一些深刻的魔法,工厂 函数可以通过调用object()创建一个实例, 插件无论它想要什么属性,然后将 __class__属性更改为它想要的任何类别 它返回新创建的实例。它没有必要接近任何类似于构造函数的东西(除了 调用object()以获得新的实例,当然。) 约束是有一些工厂函数可以创建一个Base类的实例。所以我_不能叫'Base .__ init __(self)"在 Derived .__ init__ func中,因为它们将是_two_实例(一个由Derived .__ init__创建,其他由工厂函数创建) 我想得到一个派生的类对象,但我没有允许创建Base实例,我想使用_existing_Base'的实例,然后将其用作Derived'的实例。 metaclass会解决这个问题吗? 错误的工具。元类用于设置类,而不是设置实例。 John Roth sr*************@yahoo.com (Sridhar R)在留言新闻中写道:< 93 ************************** @ posting.google。 com> ... 考虑下面的代码, 类Base(对象): 类派生(对象) : def __new __(cls,* args,** kwds):#some_factory返回Base的实例#我必须从这个实例派生! inst = some_factory()#this返回Base的实例 return inst#Oops!这不是派生的实例 def __init __(自我):#这不会被称为__new__返回Base'的实例传递 constrait有一些工厂函数可以创建一个Base类的实例。所以我_不能叫'Base .__ init __(self)"在 Derived .__ init__ func中,因为它们将是_two_实例(一个由Derived .__ init__创建,其他由工厂函数创建) 我想得到一个派生的类对象,但我没有允许创建Base实例,我想使用_existing_Base'的实例,然后将其用作Derived'的实例。 元类会解决这个问题吗? 我真的不明白你想做什么(即你想要 派生。是否要__init__?)。而且,正如其他人指出的那样,使用类工厂比使用__new__变得更干净。 如果你真的想使用元类,你可以覆盖 __call__方法,以这种方式干扰 类的实例化。例如,这是制作单身 类的代码(这是常见问题解答;) 类Singleton(类型): 这个元类的实例是单例 def __init __(cls,name,bases,dic): super(Singleton,cls).__ init __(name ,base,dic) cls.instance =无 def __call __(cls,* args,** kw): if cls。实例是无: cls.instance = super(Singleton,cls).__ call __(* args,* * kw) return cls.instance C级: __metaclass __ = Singleton 这不是你想要的,但你可以玩__call__并获得 您想要的行为。不过,为什么不只是使用一个简单的工厂? Michele Simionato Consider the code below,class Base(object):passclass Derived(object):def __new__(cls, *args, **kwds):# some_factory returns an instance of Base# and I have to derive from this instance!inst = some_factory() # this returns instance of Basereturn inst # Oops! this isn''t an instance of Deriveddef __init__(self):# This won''t be called as __new__ returns Base''s instancepassThe constrait is there is some factory function that creates aninstance of Base class. So I _can''t_ call "Base.__init__(self)" inDerived.__init__ func, as their will be _two_ instances (one createdby Derived.__init__ and other created by the factory function)Simply I want to get a derived class object, but instead of allowing_automatic_ creation of Base instance, I want to use _existing_ Base''sinstance, then use this as a Derived''s instance.Will metaclass solve this problem? 解决方案 Sridhar R wrote: Consider the code below, class Base(object): pass class Derived(object):I suppose that should beclass Derived(Base): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this instance! inst = some_factory() # this returns instance of Base# using brute force:inst.__class__ = DerivedNo guarantees, but the above seems to work. return inst # Oops! this isn''t an instance of Derived def __init__(self): # This won''t be called as __new__ returns Base''s instance pass The constrait is there is some factory function that creates an instance of Base class. So I _can''t_ call "Base.__init__(self)" in Derived.__init__ func, as their will be _two_ instances (one created by Derived.__init__ and other created by the factory function)As some_factory() returns an already initialized instance of Base, thereshould be no need to call it again from inside Derived.__init__() Simply I want to get a derived class object, but instead of allowing _automatic_ creation of Base instance, I want to use _existing_ Base''s instance, then use this as a Derived''s instance. Will metaclass solve this problem?I think metaclasses will solve only metaproblems...Skeptically yours,Peter"Sridhar R" <sr*************@yahoo.com> wrote in messagenews:93**************************@posting.google.c om... Consider the code below, class Base(object): pass class Derived(object): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this instance! inst = some_factory() # this returns instance of Base return inst # Oops! this isn''t an instance of Derived def __init__(self): # This won''t be called as __new__ returns Base''s instance pass__new__ can return an instance of any class it pleases.It''s not restricted to returning an instance of the class ithappens to be in, nor is it restricted to returning a newlycreated instance, for that matter. It can do the entireconstruction job without using the __init__ method.However, I don''t think that''s the best solution. Ifyour factory is going to return instances of severaldifferent classes, I think it''s best that it be an explicitfactory method or function, not something that magicallyhappens in a class constructor. I''d rather not have todeal with programs where class constructors pass meinstances of classes other than the one I''m calling.If you want to do a little bit of deep magic, a factoryfunction can create an instance by calling object(),plug in whatever attributes it wants and then change the__class__ attribute to whatever class it wants beforeit returns the newly minted instance. It doesn''t have togo near anything that resembles a constructor (other thancalling object() to get a new instance, of course.) The constraint is there is some factory function that creates an instance of Base class. So I _can''t_ call "Base.__init__(self)" in Derived.__init__ func, as their will be _two_ instances (one created by Derived.__init__ and other created by the factory function) Simply I want to get a derived class object, but instead of allowing _automatic_ creation of Base instance, I want to use _existing_ Base''s instance, then use this as a Derived''s instance. Will metaclass solve this problem?Wrong tool. Metaclasses are used to set up classes, not toset up instances.John Rothsr*************@yahoo.com (Sridhar R) wrote in message news:<93**************************@posting.google. com>... Consider the code below, class Base(object): pass class Derived(object): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this instance! inst = some_factory() # this returns instance of Base return inst # Oops! this isn''t an instance of Derived def __init__(self): # This won''t be called as __new__ returns Base''s instance pass The constrait is there is some factory function that creates an instance of Base class. So I _can''t_ call "Base.__init__(self)" in Derived.__init__ func, as their will be _two_ instances (one created by Derived.__init__ and other created by the factory function) Simply I want to get a derived class object, but instead of allowing _automatic_ creation of Base instance, I want to use _existing_ Base''s instance, then use this as a Derived''s instance. Will metaclass solve this problem?I don''t really understand what you want to do (i.e. do you wantDerived.__init__ to be called or not?). Moreover, as others pointedout, it is cleaner to use a class factory than to pervert __new__.If you really want to use a metaclass, you could override the__call__ method of the metaclass, in such a way to interfer with theclass instantiation. For instance, this is the code to make a singletonclass (which is a FAQ ;)class Singleton(type):"Instances of this metaclass are singletons"def __init__(cls,name,bases,dic):super(Singleton,cls).__init__(name,bases,dic)cls.instance=Nonedef __call__(cls,*args,**kw):if cls.instance is None:cls.instance=super(Singleton,cls).__call__(*args,* *kw)return cls.instanceclass C:__metaclass__=SingletonThis is not what you want but you can play with __call__ and getthe behavior you want. Still, why don''t just use a simple factory?Michele Simionato 这篇关于将基类实例转换为派生类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-25 04:37