Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Python class structure

I am trying to make my new code as user friendly as possible and what I would have in mind for the particular problem I am facing atm is this:

Suppose we have

import numpy as np
class TestClass:
 def __init__(self, data):
 self.data = data
 @property
 def method_a(self):
 return np.median(self.data)
 @property
 def method_b(self):
 return np.mean(self.data)
foo = TestClass([1, 2, 5, 7, 12, 6, 3, 37, 16])
print(foo.method_a)
print(foo.method_b)

Everything is fine so far. Method A gives me the median, method B the mean.

During processing I will switch depending on circumstances between both methods. So sometimes I will call method A, sometimes method B. However, what I want is then to continue with a method C, that acts upon the result of either method A or B in such a way

final_result = foo.method_a.method_c

or

final_result = foo.method_b.method_c

I know it is possible to write method C as a function and do it like this:

final_result = method_c(foo.method_a)
final_result = method_c(foo.method_b)

but I think it would make the code easier to read if I could apply method C as stated above.

Is this possible somehow?

thanks

Answer*

Draft saved
Draft discarded
Cancel
1
  • Humm. I did not manage to implement your ideas directly in my code, however, I dd not know that one can wrap a return value inside another class. 😊 With this I simply moved my Methods A and B to the parenting class and returned a new class for which then method C can be applied in the way I want. Hard to describe what I did, but your comment helped 😊 Commented Mar 21, 2015 at 15:20

lang-py

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /