class - Is there a way to pass arguments using the dot operator in python? -
i'd make clean, "smart" method performs specific operations without passing in arguments. have code works in principle follows:
class foo(): def __init__(self, spam='spam', ham='ham'): self.spam = spam self.ham = ham def bar(self, arg): # spam operation if arg == self.spam: return self.spam*2 # ham operation elif arg == self.ham: return self.ham*3
notice bar
method written perform different operations on spam
, ham
. implementing code return:
foo = foo() foo.bar(foo.spam) # returns 'spamspam' foo.bar(foo.ham) # returns 'hamhamham'
unfortunately, i'm having use foo
twice access specific operation in bar
, awkward , tedious. there cleaner, pythonic way same results without passing in arguments? example, possible overload dot (.) operator same results with:
# ideal 1 foo = foo() foo.bar.spam # bar knows use spam operation foo.bar.ham # bar knows use ham operation
or better
# ideal 2 foo = foo() foo.spam.bar # bar knows use spam operation foo.ham.bar # bar knows use ham operation
edit: updated parametize options.
here using object composition:
class pork(object): def __init__(self, name, mult): self.name = name self.mult = mult @property def bar(self): return self.name * self.mult def __repr__(self): return self.name class foo(object): def __init__(self, spam='spam', ham='ham'): self.spam = pork(spam, 2) self.ham = pork(ham, 3)
results:
in [638]: foo = foo() in [639]: foo.spam.bar out[639]: 'spamspam' in [641]: foo.ham.bar out[641]: 'hamhamham'
Comments
Post a Comment