Reputation: 11193
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)
Upvotes: 2
Views: 3520
Reputation: 10809
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.
Upvotes: 5
Reputation: 30473
You may use @classmethod
:
@classmethod
def createVarChar(cls, size, charSet):
return cls(dataType=SQLDataType.VARCHAR, size=size, charSet=charSet)
Upvotes: 2