Which coding style is better? public API or private method inside class definition
Neil Cerutti
neilc at norwich.edu
Wed Jan 5 11:26:14 EST 2011
On 2011-01-05, Inyeol <inyeol.lee at gmail.com> wrote:
> For example: I'm writing simple class:
>
> class Numbers:
> def __init__(self, numbers):
> self._numbers = numbers
> def get_all(self):
> for number in self._numbers:
> yield number
>
> If I want to add another method for yielding even numbers only,
> I may use:
>
> def get_even(self):
> for numbers in self._numbers:
> if numbers % 2 == 0:
> yield number
>
> or, I can use public method 'get_all' instead of using private
> attribute '_numbers', like:
>
> def get_even(self):
> for numbers in self.get_all():
> if numbers % 2 == 0:
> yield number
>
> Which coding style do you prefer? I'm more toward public API
> way, since it requires less code change if I refactor private
> data structure later. Plz give pros and cons of these.
Decoupling a member function from its own internal state would be
of little benefit.
However, decoupling an interface from its implementation can be a
good idea. Python provides inheritance and the NotImplmented
exception to help with that. Duck-typing is another popular
approach.
--
Neil Cerutti
More information about the Python-list
mailing list