简体   繁体   English

如何在python中一次定义和实例化派生类?

[英]How to define and instantiate a derived class at once in python?

I have a base class that I want to derive and instantiate together. 我有一个基类,我想一起派生和实例化。 I can do that in java like: 我可以在Java中执行以下操作:

BaseClass derivedClassInstance = new BaseClass() {
    @override
    void someBaseClassMethod() { // my statements}
};

In python I can derive and and instantiate a base class like: 在python中,我可以派生和实例化一个基类,例如:

class DerivedClass(BaseClass):
    def some_base_class_method():
        # my statements

derived_class_instance = DerivedClass()

I need to sub-class single instances of some objects with minor changes. 我需要对一些对象的单个实例进行细微的改动。 Deriving and assigning them separately seems like overkill. 分别派生和分配它们似乎过大了。

Is there a Java-like one-liner way to derive and instantiate a class on the fly? 是否有一种类似于Java的单线方式来即时派生和实例化类? Or is there a more concise way to do what I did in python? 还是有一种更简洁的方式来完成我在python中所做的工作?

In general you won't see this kind of code, because is difficult to read and understand. 通常,您不会看到这种代码,因为它很难阅读和理解。 I really suggest you find some alternative and avoid what comes next. 我真的建议您找到其他选择,并避免接下来发生的事情。 Having said that, you can create a class and an instance in one single line, like this: 话虽如此,您可以在一行中创建一个类和一个实例,如下所示:

>>> class BaseClass(object):
...     def f1(self, x):
...             return 2
...     def f2(self, y):
...             return self.f1(y) + y
... 
>>> 
>>> W = BaseClass()
>>> W.f2(2)
4
>>> X = type('DerivedClass', (BaseClass,), {'f1': (lambda self, x: (x + x))})()
>>> X.f2(2)
6

I think you are looking for metaclass programming. 我认为您正在寻找元类编程。

class Base(object):
   def test(self):
      print 'hit'
a =type( 'Derived',(Base,),{})()
a.test()
hit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM