[Tutor] Class learning

Alan Gauld alan.gauld at btinternet.com
Fri Jan 23 19:30:55 CET 2015


On 23/01/15 01:44, jarod_v6 at libero.it wrote:

> How can gave the attributes __name__ to a function?

You don't Python does it for you.


> class Foo(object):
>
>      def __init__(self):
>          steps = {}
>          tmp = open("rnaseq.base.ini","rb")
>          config.readfp(tmp)
>          readsets = parse_illumina_readset_file("/home/mauro/Desktop/readset.csv")

You realise that steps is a local variable that is not used and gets 
thrown away. So its a waste of space.
Similarly you read the config file but throw away the results.
Again a waste of space.
And the same with readsets.
Your init does a lot of work to no long term effect.

>      @property
>      def steps(self):
>          return [
>
>              self.one,
>              self.two,
>              self.fmit,
>          ]
>      def one(self):
>          a = 5
>          return a
...
>      #@property
>      def show(self):
>          ftp="\n".join([str(idx + 1) + "- " + step.__name__  for idx, step in enumerate(self.steps)])
>
>          print ftp
> It is working
>
> In [5]: F =  Foo()
>
> In [6]: F.show()
> 1- one
> 2- two
> 3- fmit

Yes, as expected.

> Why if I define the data in the same way  I have this error?
>
> <ipython-input-83-a3c57022a089> in <module>()
> ----> 1 rna.show()
>
> <ipython-input-79-b1a3b6d221ae> in show(self)
>      261         #@property
>      262         def show(self):
> --> 263                 ftp="\n".join([str(idx + 1) + "- " + step.__name__  for idx, step in enumerate(self.steps)])
>      264
>      265                 print ftp
>
> AttributeError: 'str' object has no attribute '__name__'

Because you didn't define it in the same way.

Consider this example from the pastebin:

        @property
         def star(self):
                 print "Mitico Star"
                 return "name"


Here you make star a property so when in steps you store self.star you 
are not storing a reference to the method, as you did above, you are 
storing the return value of star - "name".

Now in show() you try to take the __name__ of "name" but, as the error 
says, strings don't have __name__ attributes.

The same applies to some, but not all, of the other method names in steps...

You would make life much easier if you got rid of all the property stuff 
(some of it commented out and others not). Just use the
methods and data attributes directly, it makes life so much easier.


> Here you find all the other code the principal are the same:http://pastebin.com/nYGEiXY4


HTH
-- 
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




More information about the Tutor mailing list