是否可以使用Python进行部分继承?

编程入门 行业动态 更新时间:2024-10-25 18:35:59
本文介绍了是否可以使用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进行部分继承?

本文发布于:2023-11-30 14:53:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!