On 22/12/15 22:06, jamie hu wrote: > * > * > I am trying to write down class and object definition for a Virtual > Machine type. For example, I would like to create a Virtual Machine > (object) that can have actions like launch, terminate, stop, add_disk, > remove_disk etc.. > *
Seems reasonable. > My confusion here is that VirtualMachine object doesn't exist until it is > actually launched successfully. Most objects don't exist until they are created, so it looks like your init() method may need to call the launch code. > So should the launch method be part of > VirtualMachine class or some other VirtualMachineConfigurator class? Sounds like you just include it as part of the creation mechanism. Alternatively you can use a class method that returns a new machine instance. > Should*VirtualMachineConfigurator.launch() return VirtualMachine object In general objects should do it to themselves so I'd suggest you either 1) include the configuration as part of construction 2) configure the machine when you create it then launch(start) it after the object comes into existence 3 If (and only if) all instances will share configuration you can make the config mechanism a class method and the config settings class attributes, but that seems very unlikely. > Example class blueprint that I've been thinking: > * > class VirtualMachineConfigurator(): > * def __init__(self,memory,vcpu,network,base_image): > * * * self.memory = memory > * * * self.vcpu = vcpu > * * * self.network = network > * * * self.base_image = base_image > * > def launch(self) > * """ Launches Virtual Machine and returns VirtualMachine object """ > * try: > * * vm = hypervisor_conn.launch_vm(self.memory, self.vcpu, self.network, > self.base_image) > * * return vm > * except Exception as e: > * * raise e Just put that code into your VirtualMachine class. > class VirtualMachine(): > * def __init__(self, vmid): > * * self.vmid = vmid and add the init() code to launch() above > * def stop(self): > * * """ Stops VM""" > * ** > * def attach_disk(self): -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor