tags:

views:

59

answers:

1

Hi,

I trying my hands on python. I am trying to implement a crypto class which does enc/dec . In my crypto class i require user to pass 3 args to do the enc dec operations. Till now i was reading key from file and doing the operations. Now i want to provide a generate key function also. But problem is that to call generate keys i dont want user to provide any arguments while initiating the class.

So what essentially i am trying to achieve is that when the crypto class is instantiated without giving any arguments, i just want to expose generate_key function. and when all the 3 args are provided while instantiating class, I want to expose all other enc/dec functions but not key gen function.

I am not able to understand is it a polymorphism situation, or inheritance or should i just use 2 different classes one having generate keys and other for enc dec functions..

Please give me some suggestion about how can i handle this situation efficiently?

Example:

class crypto:
    def __init__(self,id, val1):
        self._id = id
        self._val1 = val1

    def encrypt(self):
        """ encryption here """


    def save(self):
        """ save to file """

    def load(self):
        """ load from file"""

    def decrypt(self):
        """ decryption here"""

    def gen_keys(self):
        """ gen key here"""

So Now, when this crypto class is instantiate with no arguments, i just want to expose gen keys function. and if it is instantiated with the id and val1, then i want to expose all functions but not gen keys.

I hope this will provide some clarification about my question. Please suggest me how can i achieve this.

Thanks, Jon

A: 

You want a factory with either inherited or duck-typed objects. For example:

class CryptoBasic(object):

    def __init__(self, *args):
        """Do what you need to do."""

    def basic_method(self, *args):
        """Do some basic method."""

class CryptoExtended(CryptoBasic):

    def __init__(self, *args):
        """Do what you need to do."""

    def extended_method(self, *args):
        """Do more."""

# This is the factory method
def create_crypto(req_arg, opt_arg=None):
    if opt_arg:
        return CryptoExtended(req_arg, opt_arg)
    else:
        return CryptoBasic(req_arg)
Santa