简体   繁体   中英

Python: Class Inheritance and Incoming Arguments

ClassA to inherits from Base class which inherits from built-in dict class. 'name' and 'id' are Base class attributes. 'win' and 'mac' are attributes ClassA attributes. How should I put a logic in this code so classA instance could be declared as easy as:

myInstance=ClassA(myDictArg)

===============================

class Base(dict):
    """Base is the base class from which all other classes derrive. 
    Base class inherits from build-in dict type.
    """
    id = 'id'
    name = 'name'

    def __init__(self, arg=None):
        """Initialise Base Class"""
        dict.__init__(self)
        self[Base.id] = -1
        self[Base.name] = None

        if 'id' in arg.keys() and arg['id']: self['id']=arg['id']
        if 'name' in arg.keys() and arg['name']: self['name']=arg['name']

class ClassA(Base):
    """ClassA is a class inherited from a Base class."""    
    def __init__(self, arg=None):
        if arg==None: raise Exception('arg==None')  
        Base.__init__(self)
        self.arg = arg
        # set a generic to ClassA Attrs
        self['win']=None
        self['mac']=None




myDictArg= {'id':1, 'name':'MyName', 'win':'c:/windows', 'mac': '/Volumes/mac/'}

myInstance=ClassA(myDictArg)

print myInstance

This class structure has the advantage that it keeps the signature of dict which is pretty flexible and sets default values only if they aren't provided (which I think was the original goal). It also (due to judicious use of super ) is well set up to support cooperative multiple inheritance (Horray!).

class Base(dict):
    def __init__(self, *args, **kwargs):
        super(Base, self).__init__(*args, **kwargs)
        self.setdefault('id', -1)
        self.setdefault('name', None)

class ClassA(Base):
    """ClassA is a class inherited from a Base class."""    
    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)

What you've written looks like it should work.. not that I've ran it myself. So I am making an assumption that you are looking for the bug in this situation... one possibility for a problem is the fact that you are replacing the arg variable after 'id' and 'name' have been set, effectively erasing them.. I think a better idea would be to merge the args. Although the following code may not be the most pythonic.. It might look something like this.

for key in arg.keys()
    self.arg[key] = arg[key]

another problem is that you aren't even passing in your args object into the base class's constructor. I suggest you change that to

Base.__init__(self, args)

Otherwise, arg in the Base class will revert to the default; None.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM