2021年3月24日星期三

Proper way to create a class with a large amount of variables

I have recently began to code after not doing so for years and I'm building a small project to get started again. It's a small application using a variety of crypto exchange markets dedicated APIs.

My question isn't about solving a problem it's about the proper way to solve it. Since, I dislike coding models that have a lot of variables, I decided to create an abstract model that will do the labor intensive part of defining variables for me.

Here's the question. When creating a class that requires many variables, should I:

  1. Define every variable in the __init__() method as well as include every variable in the __init__() header

    or

  2. Can I use my abstract class that only requires the defining of a list of variables that are needed and can I do this for my future projects?

My abstract class uses a 'static' list (python, I know) of variable names and implements the __init__(self, *args, **kwargs) way of building a dynamic / abstract object.

I don't know if an explicit bulky method or an implicit abstract method should be implemented for projects. What is the standard approach people/teams use in the real world?

Examples

Explicit Bulky Method

class Coin(object):      def __init__(self, id=None, base_currency=None, quote_currency=None, base_min_size=None, base_max_size=None,               quote_increment=None, base_increment=None, display_name=None, min_market_funds=None, max_market_funds=None,               margin_enabled=None, post_only=None, limit_only=None, cancel_only=None, trading_disabled=None,               status=None, status_message=None):      self.id = id      self.base_currency = base_currency      self.quote_currency = quote_currency      self.base_min_size = base_min_size      self.base_max_size = base_max_size      self.quote_increment = quote_increment      self.base_increment = base_increment      self.display_name = display_name      self.min_market_funds = min_market_funds      self.max_market_funds = max_market_funds      self.margin_enabled = margin_enabled      self.post_only = post_only      self.limit_only = limit_only      self.cancel_only = cancel_only      self.trading_disabled = trading_disabled      self.status = status      self.status_message = status_message  

Implicit abstract method

class EasyModel(object):      """ Abstract Model. Use to create models that might have extensive variable members, or in cases where applicable. """        __attrs__ = []        def __init__(self, *args, **kwargs):          self.set_using_args(args) # set variables given as a *args          self.set_using_kwargs(kwargs) # set variables given as **kwargs          self.fill_empty() # Set variables that were expected to None        def set_using_args(self, args):          """ Given a list of variables (assuming in the correct order), add the value to the proper variable name. """          for i, arg_value in enumerate(args):              arg_name = self.__class__.__attrs__[i]              setattr(self, arg_name, arg_value)        def set_using_kwargs(self, kwargs):          """ Given a dictionary, add the parameters as variables to the instance if the parameter is valid. """          for arg_name, arg_value in kwargs.items():              if (arg_name in self.__class__.__attrs__):                  setattr(self, arg_name, arg_value)        def fill_empty(self):          """ Create any undefined variables and set as None """          for arg_name in self.__class__.__attrs__:              if (not hasattr(self, arg_name)):                  setattr(self, arg_name, None)        def __setattr__ (self, name, value):          """ Make sure that the attributes that will be added are expected. """          if (name in self.__class__.__attrs__):              self.__dict__[name] = value      class Coin(EasyModel):      """ Using the EasyModel to quickly build a model that will be created from an API request that gives all the data below in the form of a dictionary. """        __attrs__ = ['id', 'base_currency', 'quote_currency', 'base_min_size', 'base_max_size',                   'quote_increment', 'base_increment', 'display_name', 'min_market_funds', 'max_market_funds',                   'margin_enabled', 'post_only', 'limit_only', 'cancel_only', 'trading_disabled', 'status', 'status_message']        def __init__(self, *args, **kwargs):          super(Coin, self).__init__(*args, **kwargs)    # Both would result in the same usage.  coin_data = {...} # Json / dictionary version of object    # Create object by passin json / dictionary as **kwargs  c = Coin(**coin_data)    # Both methods would result in this usage.  print (c.display_name)  
https://stackoverflow.com/questions/66727611/proper-way-to-create-a-class-with-a-large-amount-of-variables March 21, 2021 at 07:54AM

没有评论:

发表评论