2

I am trying to create DataType class to reflect data types in a SQL database. Since data types require different information like size, precision etc. different parameters need to be specified when creating an instance.

I want to be able to call it with something like DataType.createVarChar(size, charSet). So far I have written the code below but I am not sure whether it is the correct way to do it since I am originally creating an object at the start without providing any information in it.

What would be the correct design in this case?

class SQLDatatype(Enum):
    UNSUPPORTED,
    VARCHAR


class DataType(object):

    def __init__(self, dataType=None, precision=None, scale=None, size=None, charSet=None):
        self.dataType = dataType
        self.precision = precision
        self.scale = scale
        self.size = size
        self.withLocalTimezone = withLocalTimezone
        self.charSet = charSet

    def createVarChar(self, size, charSet):
        return Datatype(dataType=SQLDataType.VARCHAR, size=size, charSet=charSet)

2 Answers 2

5

The standard way would be to create a function:

def createVarChar(size, charSet):
    return Datatype(dataType=SQLDataType.VARCHAR, size=size, charSet=charSet)

The other option is to create a class method:

class DataType(object):
    ...
    @classmethod
    def createVarChar(cls, size, charSet):
        return cls(dataType=SQLDataType.VARCHAR, size=size, charSet=charSet)

This allows this method to work correctly with inheritance, which a free function would not.

Sign up to request clarification or add additional context in comments.

1 Comment

okay lets say i for instance wanted to have a toString() function inside the class aswell where i converted the datatype to for instance varchar({}).format(size) would that mean i had to make the def createVarChar outside or can is there anyway where i can get dataType inside another function in class?
2

You may use @classmethod:

@classmethod
def createVarChar(cls, size, charSet):
    return cls(dataType=SQLDataType.VARCHAR, size=size, charSet=charSet)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.