Re: mutually exclusive arguments to a constructor
- From: Jason Friedman <jason@xxxxxxxxxxxxx>
- Date: Fri, 30 Dec 2011 21:18:29 +0000
Suppose I'm creating a class that represents a bearing or azimuth,
created either from a string of traditional bearing notation
("N24d30mE") or from a number indicating the angle in degrees as
usually measured in trigonometry (65.5, measured counter-clockwise
from the x-axis). The class will have methods to return the same
bearing in various formats.
In Java, I would write two constructors, one taking a single String
argument and one taking a single Double argument. But in Python, a
class can have only one __init__ method, although it can have a lot of
optional arguments with default values. What's the correct way to
deal with a situation like the one I've outlined above?
Similar to other answers already posted:
#!/usr/bin/env python
class azimuth:
def __init__(self, bearing, heading):
self.bearing = bearing
self.heading = heading
if not bearing:
self.bearing = 30.5 # or, realistically, a calculation
based on the heading
if not heading:
self.heading = "N..." # or, realistically, a calculation
based on the bearing
@staticmethod
def getBearingInstance(bearing):
return azimuth(bearing, None)
@staticmethod
def getHeadingInstance(heading):
return azimuth(None, heading)
azimuth1 = azimuth.getBearingInstance("N24d30mE")
print azimuth1.heading
azimuth2 = azimuth.getHeadingInstance(30)
print azimuth2.bearing
.
- Follow-Ups:
- Re: mutually exclusive arguments to a constructor
- From: Steven D'Aprano
- Re: mutually exclusive arguments to a constructor
- References:
- mutually exclusive arguments to a constructor
- From: Adam Funk
- mutually exclusive arguments to a constructor
- Prev by Date: Re: mutually exclusive arguments to a constructor
- Next by Date: Re: How to get function string name from i-th stack position?
- Previous by thread: Re: mutually exclusive arguments to a constructor
- Next by thread: Re: mutually exclusive arguments to a constructor
- Index(es):
Relevant Pages
|