Class Not Auto-Init On Import

Steve Holden steve at holdenweb.com
Sat Apr 21 11:56:05 EDT 2007


Robert Rawlins - Think Blue wrote:
> Hello Guys,
> 
>  
> 
>  From my understanding of what I’ve read, the ‘import’ is meant to auto 
> Init my class ready for me to access its methods, but it doesn’t appear 
> too, I’m having to init them myself before I can access them, like this.
> 
Importing a module (the first time) executes its code. This means that 
assignments bind to names in the module's namespace, class statements 
define classes in the module's namespace, def statements define 
functions in the module's namespace. The statement
> 
> import LocationService
> 
after, running the module's code, makes the module's namespace available 
as the name LocationService in the importing module's namespace. So 
"name" in the module's namespace can be referred to in the importing 
module as LocationService.name.
> 
> Location = LocationService.LocationService()
> 
So that statement creates an instance of the LocationService class 
defined in the LocationService module. Since no arguments are provided, 
the new instance's __init__() method is called with a single argument, 
the new instance itself.
> 
> LocationService.setIP(‘192.168.1.1’)
> 
This isn't a call on a specific LocationService instance, it's a call on 
the SetIP method of the class (presumably you have to set the IP address 
of the server or whatever - typically class methods are used to invoke 
functions or set up conditions that must apply to all instances of the 
class. If you wanted to set the IP for a particular instance you would 
normally call a method instance, as in

Location.SetIP('129.168.1.1')

But if the class defines the method as a class method then a call like 
the above is likely to fail. So it's ultimately all down to the design 
of the class you are using.
> 
> Why is this the case? Should i not just be able to access the setIP() 
> method by doing LocationService.setIP(‘192.168.1.1’) Without having to 
> create my own inited reference?
> 
That would make a certain amount of sense, but whether this would be 
acceptable depends how the class's __init__ method is defined. There's 
certainly nothing in the Python language that would *stop* you doing that.

It seems that there might be a certain amount of confusion, either in 
your mind or in the module you are using, between object-oriented 
programming techniques and the more process-oriented traditional 
techniques. I don't know whether this will have helped or not.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list