Note that there are some explanatory texts on larger screens.

plurals
  1. POFactory method for objects - best practice?
    text
    copied!<p>This is a question regarding the best practice for creating an instance of a class or type from different forms of the same data using python. Is it better to use a class method or is it better to use a separate function altogether? Let's say I have a class used to describe the size of a document. (Note: This is simply an example. I want to know the best way to create an instance of the class <strong>not</strong> the best way to describe the size of a document.)</p> <pre><code>class Size(object): """ Utility object used to describe the size of a document. """ BYTE = 8 KILO = 1024 def __init__(self, bits): self._bits = bits @property def bits(self): return float(self._bits) @property def bytes(self): return self.bits / self.BYTE @property def kilobits(self): return self.bits / self.KILO @property def kilobytes(self): return self.bytes / self.KILO @property def megabits(self): return self.kilobits / self.KILO @property def megabytes(self): return self.kilobytes / self.KILO </code></pre> <p>My <code>__init__</code> method takes a size value represented in bits (bits and only bits and I want to keep it that way) but lets say I have a size value in bytes and I want to create an instance of my class. Is it better to use a class method or is it better to use a separate function altogether?</p> <pre><code>class Size(object): """ Utility object used to describe the size of a document. """ BYTE = 8 KILO = 1024 @classmethod def from_bytes(cls, bytes): bits = bytes * cls.BYTE return cls(bits) </code></pre> <p>OR</p> <pre><code>def create_instance_from_bytes(bytes): bits = bytes * Size.BYTE return Size(bits) </code></pre> <p>This may not seem like an issue and perhaps both examples are valid but I think about it every time I need to implement something like this. For a long time I have preferred the class method approach because I like the organisational benefits of tying the class and the factory method together. Also, using a class method preserves the ability to create instances of any subclasses so it's more object orientated. On the other hand, a friend once said "When in doubt, do what the standard library does" and I am yet to find an example of this in the standard library.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload