Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a class containing related member variables efficiently?

Tags:

python

oop

Suppose I want a class named Num which contains a number, its half, and its square.

I should be able to modify any of the three variables and it will affects all of its related member variables. I should be able to instantiate the class with any of the three value.

What is the best way to design this class so that it can be modified easily and ensure that I will not leave something behind?

Should I store all the three numbers or just store the main number?

For example, this is how I will use my class in Python:

num = Num(5)
print num.n, num.half, num.square

And it should print 5, 2.5 and 25

That's simple but I also want to initialize with its half.

num = Num(half=2.5)
print num.n, num.half, num.square

And it should also print 5, 2.5 and 25

How can I make the init function know that it's a half?

And I also want to modify any of the number and it will change all related numbers! E.g.:

num.square = 100
print num.n, num.half, num.square

And it should print 10, 5 and 100.

How can I design the class?

like image 636
off99555 Avatar asked Aug 09 '15 13:08

off99555


People also ask

What are member variables in a class?

In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).

What is a class how can we identify classes during program design?

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).

What is a class design?

A design class represents an abstraction of one or several classes in the system's implementation; exactly what it corresponds to depends on the implementation language. For example, in an object-oriented language such as C++, a class can correspond to a plain class.


1 Answers

Same solution as @Daniel - expanded, lambda-less, Python 3.3:

class Num:
#class Num(object): for Python 2.
    def __init__(self, n = None, half = None, square = None):
        if n is not None:
            self.n = n
        elif half is not None:
            self.half = half
        elif square is not None:
            self.square = square
        else:
            self.n = 0

    @property
    def n(self):
        return self.__n
    @n.setter
    def n(self, n):
        self.__n = n
    @property
    def half(self):
        return self.n / 2.0
    @half.setter
    def half(self, n):
        self.n = n * 2
    @property
    def square(self):
        return self.n ** 2
    @square.setter
    def square(self, n):
        self.n = n ** .5

>>> five = Num(n=5)
>>> five.half, five.n, five.square, five._Num__n
(2.5, 5, 25, 5)
>>>
like image 153
wwii Avatar answered Oct 09 '22 03:10

wwii