Saturday, 15 March 2014

class - Python classes and how to use them style-wise -



class - Python classes and how to use them style-wise -

i've been programming in python time , have covered knowledge in python style still have problem on how utilize classes properly. when reading object oriented lecture find rules single responsibility principle state

"the single responsibility principle says class should have one, , one, reason change"

reading this, might think of breaking 1 class two, like:

class complicatedoperations(object): def __init__(self, item): pass def do(self): ... ## lots of other functions class createoption(object): def __init__(self, simple_list): self.simple_list = simple_list def to_options(self): operated_data = self.transform_data(self.simple_list) homecoming self.default_option() + operated_data def default_option(self): homecoming [('', '')] def transform_data(self, simple_list): homecoming [self.make_complicated_operations_that_requires_losts_of_manipulation(item) item in simple_list] def make_complicated_operations_that_requires_losts_of_manipulation(self, item): homecoming complicatedoperations(item).do()

this, me, raises lots of different questions; like:

when should utilize class variables or pass arguments in class functions? should complicatedoperations class class or bunch of functions? should __init__ method used calculate final result. makes class hard test. what rules pythonists?

edited after answers:

so, reading augusto theory, end this:

class complicatedoperations(object): def __init__(self): pass def do(self, item): ... ## lots of other functions def default_option(): homecoming [('', '')] def complicate_data(item): homecoming complicatedoperations().do(item) def transform_data_to_options(simple_list): homecoming default_option() + [self.complicate_data(item) item in simple_list]

(also corrected little bug default_option.)

when should utilize class variables or pass arguments in class functions

in illustration pass item do method. also, related programming in language, give class info needs (least authority), , pass not internal algorithm via parameters (depedency injection), so, if complicatedoperations not need item initialize itself, not give init parameter, , if needs item it's job, give parameter.

should complicatedoperations class class or bunch of functions

i'd say, depends. if you're using various kinds of operations, , share sort of interface or contract, absolutely. if operation reflects concept , methods related class, sure. if loose , unrelated, might utilize functions or think 1 time again single responsability , split methods other classes

should init method used calculate final result. makes class hard test.

no, init method initialization, should work on separated method.

as side note, because of lack of context, did not understand createoption's role. if used show above, might remove ...

python class

No comments:

Post a Comment