Python Forum
Manipulating __init__ method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Manipulating __init__ method
#1
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?
Reply
#2
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.
Reply
#3
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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
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]
Reply
#5
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]
Reply
#6
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Manipulating panda dataframes more python-like badtwistoffate 4 2,022 Jan-31-2023, 04:30 AM
Last Post: deanhystad
  Manipulating code to draw a tree Py_thon 8 3,224 Nov-21-2019, 05:00 PM
Last Post: sumana
  Manipulating List frenchyinspace 2 2,651 Oct-08-2019, 07:57 AM
Last Post: perfringo
  Extend my __init__ method by an extra parameter Tol duyduy 8 3,970 Jun-04-2019, 06:47 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020