On Jan 4, 8:46 pm, Inyeol <inyeol....@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.
Using Public API makes it easier to subclass, if you want to redefine the meaning of "all" somehow. The main reason to avoid Public API is to get performance benefits (most Python built-in classes access the internal structure directly for this reason). There are occasions where a function really needs to access the internals and not the "visible" value. Also, in Python it's reasonable to consider an instance variable to be part of the public interface of a class, because backwards- incompatible changes can be avoided using properties. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list