Starting Python... some questions

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Mar 13 04:40:43 EDT 2007


Steven D'Aprano a écrit :
> 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

s/Class/Instance/

classmethods are methods that takes the class as first parameter.

> always take a first parameter that points to the
> class instance. 

(snip)

> Just remember to always put "self" as the first argument to a class
> method, 

idem.



More information about the Python-list mailing list