如何继承类的方法并让它们在python中访问自己的成员变量
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何继承类的方法并让它们在python中访问自己的成员变量,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2609字,纯文字阅读大概需要4分钟。
内容图文
![如何继承类的方法并让它们在python中访问自己的成员变量](/upload/InfoBanner/zyjiaocheng/791/d7e8841a76d8406a9c3a29f33de7172e.jpg)
我是Python的新手,我一直试图找出将一堆凌乱的类方法(访问成员变量)迁移到一个单独的Utils.py类型模块中以清理的最佳方法.方法名称仍然需要由基类继承,但是它们还需要访问parnet类方法.我正在详细介绍背景,因为我认为可能有更好的python方法来解决这个问题.
基本上我需要做类似下面的事情,如果我试图通过继承做到这一点:(我玩过超级,但我无法用这种方式解决)
class Graph(GraphUtils):
graph_size = 10
def print_size(self):
print self.graph_size
class GraphUtils():
def set_size(self, new_size)
self.graph_size = new_size
if __name__ == "__main__":
g = Graph()
print "Graph default size: " + str(g.graph_size) # This is 10
g.set_size(20)
g.print_size() # I want it to print 20, but it'll print the default 10
我知道还有另一种方法来统一将类的方法和变量导入另一个类,但是我运行了冒险命名空间冲突.
我在类似情况下使用的一种技术,其中需要一个单独的模块作为我们库中的“附加组件”显示如下:(‘附加’的想法来自于希望可选地将附加功能分配给图表类,所有许可相关)
class Graph:
ext = None
graph_size = 10
def __init__(self):
self.ext = Extension()
self.ext._graph = self
def set_size(self, new_size):
self.graph_size = new_size
class Extension:
_graph = None
def process(self):
print "Processing graph size: " + str(self._graph.graph_size)
if __name__ == "__main__":
g = Graph()
print "Graph default size: " + str(g.graph_size) # This is 10
g.set_size(20)
g.ext.process()
# Output: Processing graph size: 20
只是想知道你们认为什么是最好的方法,或者是否可以在Python中合理(安全)完成. (2.6)
谢谢!
解决方法:
解决方法是在类的__init __()方法中定义变量,并确保初始化继承的对象.
__init __()是一个’魔术’类方法,在从类定义创建新对象时调用该方法.
# Inherit object for new-style Python classes (recommended)
class GraphUtils(object):
# Override the __init__() magic-method.
def __init__(self):
# Initialize the inherited object by executing its __init__() method.
super(GraphUtils, self).__init__()
def set_size(self, new_size):
self.graph_size = new_size
# Inherit GraphUtils
class Graph(GraphUtils):
def __init__(self):
# Initialize the inherited GraphUtils object.
super(Graph, self).__init__()
# Declare the graph_size variable on creation of a new Graph object.
self.graph_size = 10
def print_size(self):
print self.graph_size
if __name__ == "__main__":
g = Graph()
# It is recommended to use str.format() instead of string concatonation
print "Graph default size: {}".format(g.graph_size) # will print "Graph default size: 10"
g.set_size(20)
g.print_size() # This will print 20
http://docs.python.org/reference/datamodel.html#basic-customization
http://docs.python.org/glossary.html#term-new-style-class
http://docs.python.org/library/functions.html#super
http://docs.python.org/library/string.html#string-formatting
内容总结
以上是互联网集市为您收集整理的如何继承类的方法并让它们在python中访问自己的成员变量全部内容,希望文章能够帮你解决如何继承类的方法并让它们在python中访问自己的成员变量所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。