Python Forum

Full Version: Manipulating __init__ method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Consider the class Interval below:

class Interval:
    def __init__(self,a,b):
        self.left=a
        self.right=b
    def __repr__(self):
        return '[{},{}]'.format(self.left,self.right)
For given numbers a and b, when printing Interval(a,b) I get:
Output:
[a,b]
However, I also want to be able to get the below output when printing Interval(number):
Output:
[number,number]
What constraints do I need to make on the __init__ method?
a and b are visible only to the __init__ method but you can access left and right outside of the class, but you must know what their values are when you instantiate the class. So I really don't quite understand. please show where you print the values.
class Interval:
    def __init__(self,a,b=None):
        self.left=a
        if b is None:
            self.right = a
        else:
            self.right=b
    def __repr__(self):
        return '[{},{}]'.format(self.left,self.right)
Sorry if I was unclear, but your replies have led me to the following solution.

class Interval:
    def __init__(self,a,b=None):
        self.left=a
        self.right=a
        if b is not None:
            self.left=a
            self.right=b
    def __repr__(self):
        return '[{},{}]'.format(self.left,self.right)
print(Interval(2))
Output:
[2,2]
can be written as
class Interval2:

    def __init__(self, a, b=None):
        self.left = a
        self.right = b or a

    def __repr__(self):
        return f'[{self.left},{self.right}]'


print(Interval2(2))
Output:
[2,2]
if you don't like the else part and don't mind to assign to self.right twice, why not simply
    def __init__(self,a,b=None):
        self.left = a
        self.right = b
        if b is None:
            self.right = a