JavaMonster class maker

Updated TrustyTony 0 Tallied Votes 259 Views Share

This code is giving minimal change from real Python class to JavaMonster with every method having setter and getter not following the PEP8 naming but capitalizedWordsFormat.

When instrunctor turns his head or if you put the code in your library, you can simply remove the setter/getter lines.

import functools

def JavaMonster(self,attribs):
    for name, func in ('set%s', setattr), ('get%s', getattr):
        for attr in attribs:
            setattr(self, name % attr.title(), functools.partial(func, self, attr))

class Pet(object):
    attribs = ('name','type','age')

    def __init__(self,**kwargs):
        if all(arg in self.attribs for arg in kwargs.keys()):
            self.__dict__.update(kwargs)
        else:
            raise ValueError('Incorrect pet attribute error: %s' % ', '.join(kwargs.keys()))
        JavaMonster(self, self.attribs)
        
    def __str__(self):
        return ('Pet(' +
               ', '.join('%s=%r' % (name, item)
                         for name, item in self.__dict__.items() if 'functools' not in str(item)) +
               ')'  )
    
def main():
    prompt = 'Please enter your pets %s: '
    mypet = Pet(name=raw_input(prompt % 'name'),
                type=raw_input(prompt % 'type'),
                age=int(raw_input(prompt % 'age'))
                )

    print mypet
    mypet.setType('dog')
    print mypet
    print 'Pets age is: %i' % mypet.getAge()
    try:
        print Pet(name = 'Nice teacher', profession = 'Java teacher')
    except ValueError as e:
        print e
main()

""" Output:
Please enter your pets name: Miso
Please enter your pets type: cat
Please enter your pets age: 6
Pet(name='Miso', age=6, type='cat')
Pet(name='Miso', age=6, type='dog')
Pets age is: 6
Incorrect pet attribute error: profession, name
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.