首页 / PYTHON / Python继承的类型变量
Python继承的类型变量
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python继承的类型变量,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1427字,纯文字阅读大概需要3分钟。
内容图文
![Python继承的类型变量](/upload/InfoBanner/zyjiaocheng/659/aa1e86a296a04ade87b792fb7a8ef0b4.jpg)
我想我误会了Python中类型继承的工作方式.
当我在Parent类中定义变量时,任何在Parent中继承的Child类
从父级引用相同的变量.
class Parent(object):
store = dict()
class ChildA(Parent):
pass
class ChildB(Parent):
pass
ChildA.store['key1'] = 'val'
ChildB.store['key2'] = 'val'
print ChildB.store['key1'] == ChildA.store['key2']
我想要实现的是要在从Parent继承的每个Child类中创建商店字典实例.因此,引用ChildB.store [‘key1’]将引发KeyError
我尝试在创建类型时使用__new__创建字典实例:
class NewParent(object):
def __new__(cls, *args, **kwargs):
rv = super(NewParent,cls).__new__(cls, *args, **kwargs)
rv.store = dict()
return rv
但这似乎是__new__仅在实例化Child类之前运行,因此通过类型引用变量(例如Child.store引发AttributeError)
那么有什么方法可以实现我想要的行为?
解决方法:
您想使用一个元类,它使您可以初始化类定义,就像构造函数如何初始化实例一样.有关更多详细信息,请参见http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/.
例:
#!/usr/bin/env python2
class ParentMeta(type):
def __new__(meta, name, bases, dct):
dct['store'] = dict()
return super(ParentMeta, meta).__new__(meta, name, bases, dct)
class Parent(object):
__metaclass__ = ParentMeta
class ChildA(Parent):
pass
class ChildB(Parent):
pass
ChildA.store['key1'] = 'val'
ChildB.store['key2'] = 'val'
print ChildB.store['key1'] == ChildA.store['key2']
将导致
Traceback (most recent call last):
File "test.py", line 20, in <module>
print ChildB.store['key1'] == ChildA.store['key2']
KeyError: 'key1'
内容总结
以上是互联网集市为您收集整理的Python继承的类型变量全部内容,希望文章能够帮你解决Python继承的类型变量所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。