Starting Python... some questions

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Mar 13 01:12:11 EDT 2007


On Mon, 12 Mar 2007 21:39:11 -0700, jezonthenet wrote:

> I started using Python a couple of days ago - here are a few
> questions:
> 
> * Doesn't the __main__() method automatically execute when I run my
> python program?


No. 


> * Only when I do an import of my test.py file within python and then
> run test.__main__() I can see where my bugs are. Is this correct?
> (right now this is my only way of running my python program and see
> where I have problems)

That's a good way of choosing to run __main__ manually, but there are
other ways.

If you add a line to the end of your program:

__main__()


the function will be executed whenever the program runs. That is both when
you import it, and when you run it from the command line.

To ensure it doesn't run when you import, do this:


if __name__ == "__main__":
    __main__()



> * Once I've done an import and then I wish to make a change to the
> file I've imported I have to quit Python, restart and import that
> module again in order for the module to be refreshed. Is there no "re-
> import" ?

Yes there is. Do this:

import my_module
# do things
# edit the file
# don't forget to save changes (that always catches me out)
reload(my_module)


> * Finally, could someone tell me why I'm having problems with the
> small module below?
>   - Python pretends I provide chassis_id() with three parameters, even
> though I clearly only provide it with two - why?
> 
> Thanks!
> 
> #!/usr/bin/python
> import scapy
> import struct
> 
> class lldp_class:
> 	def __init__(self):
> 		self.chassis_id_tlv = None
> 
> 	def chassis_id(subtype, chassis_info):
> 		if subtype == 4:
> 			chassis_data = struct.pack("!B",chassis_info)
> 		subtype_data = struct.pack("!B",subtype)
> 		self.chassis_id_tlv = subtype_data + chassis_data

Class methods always take a first parameter that points to the
class instance. By convention, it should be called "self". So you should
write this as:

    def chassis_id(self, subtype, chassis_info):
        if subtype == 4:
            chassis_data = struct.pack("!B",chassis_info)
            subtype_data = struct.pack("!B",subtype)
            self.chassis_id_tlv = subtype_data + chassis_data


When you call the method:

my_instance = lldp_class()
my_instance.chassis_id(4, "01:80:C2:00:00:0E")

Python automatically fills in a reference to the instance and calls this:

lldp_class.chassis_id(my_instance, 4, "01:80:C2:00:00:0E")


Just remember to always put "self" as the first argument to a class
method, and you will (almost never) go wrong!



-- 
Steven D'Aprano 




More information about the Python-list mailing list