Python:嵌套类继承 [英] Python: Nested Class Inheritance
问题描述
从Base(super?)类声明一个子类的实例是可以的,因为我在这里:
Would it be OK to declare an instance of the sub-classed class from its Base (super?) class as I do it here:
if 'classB_args' in dictArg.keys() and dictArg['classB_args']:
self['classB']=ClassA( dictArg['classB_args'] )
这样做有没有任何副作用?前进之前我应该注意什么。我有一种感觉迟早会发生什么问题...用cPickle,pickle或者可能是一个PyQt拖和下降?如果是,那么为什么会出现问题?
Are there any side effects of doing so? What should I be aware before moving forward. I have a feeling sooner or later something would go wrong... with cPickle , pickle or may be it would be a PyQt drag-and-dropt?.. if so then why would the problem arise?
class Base(dict):
def __init__(self, *args, **kwargs):
super(Base, self).__init__(*args, **kwargs)
self.setdefault('id', -1)
self.setdefault('name', None)
self.setdefault('classB', None)
if not args or len(args)==0: return
dictArg=args[0]
if 'classB_args' in dictArg.keys() and dictArg['classB_args']:
self['classB']=ClassA( dictArg['classB_args'] )
def getClassB(self):
return self['classB']
class ClassA(Base):
def __init__(self, *args, **kwargs):
if not (args or kwargs): raise Exception('you need to give me *something*!')
super(ClassA, self).__init__(*args, **kwargs)
self.setdefault('win', None)
self.setdefault('mac', None)
myDictArg= {'id':1, 'name':'MyName', 'win':'c:/windows', 'mac': '/Volumes/mac/', 'classB_args': {'id':1, 'name':'MyProject'}}
myInstance=ClassA(myDictArg)
print myInstance.getClassB()
推荐答案
工作,答案是肯定的,但我不能想到这是一个好主意的情况。原因是,这锁定你的基类,真正只有有用的 ClassA
...我认为解决方案可能会更干净,做一些像:
If you're asking whether it will work, the answer is yes, but I can't think of a situation where it is a good idea. The reason is that this locks your base class down to being really only useful with ClassA
... I think that the solution would probably be cleaner to do something like:
myDictArg = {'id':1, 'name':'MyName', 'win':'c:/windows', 'mac': '/Volumes/mac/', 'classB': ClassA(id=1, name='MyProject')}
并放弃 Base .__ init __
中的所有额外 classB_args
它更明确,所以用户最终知道什么期望。
and forgo all of the extra classB_args
craziness in Base.__init__
. It's more explicit so the user ends up knowing what to expect.
如果你真的不喜欢,你可以使用 self
的类型来决定使用什么比直接指定 更好的 ClassA
:
If you really don't like that, you could use the type of self
to determine what to use rather than specifying ClassA
directly which is a little better:
self['classB'] = type(self)(dictArg['classB_args'])
现在,如果从 Base
中派生一个新类,将会改为:
Now, if you derive a new class from Base
, that will be used instead:
class Foo(Base): pass
instance = Foo(myDictArg)
print type(instance.getClassB()) # Foo !
a few other non-related points.
- 不要在dct.keys()中执行
x
- 可怕在python2.x中无效。 c> - 一般来说,编写简单的包装器如
getClassB
被认为是unpythonic。 - 您可以重写
if
子句来清除它:
- Don't do
x in dct.keys()
-- It's horribly inefficient in python2.x. You can just dox in dct
:-). - Generally speaking, writing simple wrappers like
getClassB
are considered "unpythonic". You can just access the data directly in python. - You can rewrite the
if
clause to clean it up a little:
如下:
if 'classB_args' in dictArg.keys() and dictArg['classB_args']:
self['classB']=ClassA( dictArg['classB_args'] )
转到:
# with this, you can remove the `self.setdefault('classB', None)` statement.
item = dictArg.get('classB_args')
self['classB'] = type(self)(item) if item else item
这篇关于Python:嵌套类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!