是否可以使用Python进行部分继承? [英] Is it possible to do partial inheritance with Python?

查看:620
本文介绍了是否可以使用Python进行部分继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中创建一个类(class0),目前基于一个类(class1);然而,我想继承另一个类(class2)。关于class2的事情是,我不想要所有的方法和属性,我只需要一个单一的方法。 class0是否可能只继承一个单独的方法从class2?

解决方案

使用另一个类来实现所需方法的mixin方法在这种情况下是正确的。
但是为了完整性,因为它完全回答你的问题,我补充说,是的,有可能有一个行为,就像你想要的部分继承(但请注意,这样的事情不存在)。



所有要做的是在新类上添加成员,引用你想要重复的方法或属性:

  class Class2(object):
def method(self):
print(I am method at%s%self .__ class__)

class Class1(object):
pass

class Class0(Class1):
method = Class2 .__ dict __ [method]

ob = Class0()
ob.method()

注意,在Python 2.x(最多2.7)中需要从类 __ dict __ 中检索方法 - 由于运行时变换转换方法中的函数。在Python 3.0及更高版本中,只需更改

  method = Class2 .__ dict __ [method] 



  method = Class2.method 


I'm creating a class (class0) in Python that is a currently based off of one class (class1); however, I'd like to inherit from another class as well (class2). The thing about class2 is that I don't want all of it's methods and attributes, I just need one single method. Is it possible for class0 to only inherit a single method form a class2?

解决方案

The "mixin" method of having another class that just implemetns the method you want is the correct thing to do in this case. But for sake of completeness, as it answers exactly what you are asking, I add that yes, it is possible to have a behavior just like the "partial inheritance" you want (but note that such a thing does not exist).

All one have to do is to add member on the new class that refer to to the method or attribute you wish to repeat there:

class Class2(object):
   def method(self):
      print ("I am method at %s" % self.__class__)

class Class1(object):
   pass

class Class0(Class1):
   method = Class2.__dict__["method"]

ob = Class0()
ob.method()

Note that retrieving the method from the class __dict__ is needed in Python 2.x (up to 2.7) - due to runtime transforms that are made to convert the function in a method. In Python 3.0 and above, just change the line

method = Class2.__dict__["method"]

to

method = Class2.method

这篇关于是否可以使用Python进行部分继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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