I am working with 2 classes defined as zone
and system
. The system
is supposed to contain several zones, but the number can vary. So, I have defined for example the class zon开发者_如何学编程e
as such:
class zone(object):
def __init__ (self,
nameZone = None,
height = None,
width = None):
self.nameZone = nameZone
self.height = height
self.width = width
and the class system
as follows:
class system(object):
def __init__(self,
SystemName = None,
NumberOfZones = None,
zone = None):
self.SystemName = SystemName
self.NumberOfZones = NumberOfZones
self.zone = zone
So for example I would like to know how do I go about defining the class SYSTEM with a variable number of parameters? Like for example I could have:
building = system(2, apart1, apart2)
building2 = system(3, apart1,apart2,apart3)
where of course apart1, 2, and 3 are defined as class zone
.
I have tried something like:
for i in range(self.NumberOfZones)
self.zone = zone
But this doesn't work obviously.
You can use the variable args features.
class system(object):
def __init__(self, SystemName, *zones):
self.SystemName = SystemName
self.zones = list(zones)
# The number of zones is the length of the zones list.
Then you can just put any number, without even having to specify how many. Python will just collect all paramenters after the name as zones.
class System(object):
def __init__(self, system_name = None, *zones):
self.system_name = system_name
self.number_of_zones = len(zones)
self.zones = zones
I cleaned up to PEP8 slightly and left in number_of_zones.
Using the varargs is OK, but I would say it is clearer to pass explicitly a list of zones. That way you can add different named parameters in the future if needed.
精彩评论