IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

class: modifier une var d'instance avec une méthode


Sujet :

Python

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    91
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 91
    Points : 65
    Points
    65
    Par défaut class: modifier une var d'instance avec une méthode
    Bonjour,

    Je souhaite pouvoir modifier une variable d'instance avec une méthode:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    # -*- coding: utf-8 -*-
    """
    Created on Thu Sep 29 13:23:42 2011
    """
     
    class Toto():
        def __init__(self):
            self.a=0
            self.b=None
        def set_b(self,valeur):
            self.b=valeur
            #print self.b
    def main():
        t=Toto
        t.set_b(5)
        print "t.b=5?",t.b
    if __name__ == '__main__': main()
    et cela coince avec le massage suivant:
    t.set_b(5)
    TypeError: unbound method set_b() must be called with Toto instance as first argument (got int instance instead)
    Quelle est la bonne façon pour que t.b=5?
    merci

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    91
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 91
    Points : 65
    Points
    65
    Par défaut
    J'ai la même erreur avec
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    # -*- coding: utf-8 -*-
    """
    Created on Thu Sep 29 13:23:42 2011
    """
     
    class Toto():
        def __init__(self):
            self.a=0
            self.b=None
            self.c=None
    #    def set_b(self,valeur):
    #        self.b=valeur
            #print self.b
        def do_thing(self):
            self.c=self.a+self.b
    def main():
        t=Toto
        t.b=5
        print "t.b=5?",t.b
        t.do_thing()
        print t.c
    if __name__ == '__main__': main()

  3. #3
    Expert éminent
    Avatar de tyrtamos
    Homme Profil pro
    Retraité
    Inscrit en
    Décembre 2007
    Messages
    4 461
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Retraité

    Informations forums :
    Inscription : Décembre 2007
    Messages : 4 461
    Points : 9 248
    Points
    9 248
    Billets dans le blog
    6
    Par défaut
    Bonjour,

    Pour que t devienne une instance de la classe Toto, il faut faire t=Toto() et non t=Toto.
    Un expert est une personne qui a fait toutes les erreurs qui peuvent être faites, dans un domaine étroit... (Niels Bohr)
    Mes recettes python: http://www.jpvweb.com

  4. #4
    Membre éprouvé

    Homme Profil pro
    Diverses et multiples
    Inscrit en
    Mai 2008
    Messages
    662
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Diverses et multiples

    Informations forums :
    Inscription : Mai 2008
    Messages : 662
    Points : 1 273
    Points
    1 273
    Par défaut
    Ton code ne peut pas marcher*! Tu essayes, comme tu le dis toi-même, d’accéder à des variables d’instances à partir d’un objet type*! Cela revient à peu près à demander la vitesse actuelle de la voiture X à son constructeur…

    Les seules variables que tu puisses affecter dans un objet type, ce sont les variables de classes*! Par exemple*:

    Code python : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    class Test(object):
        A = None
     
        def __init__(self):
            a = None
     
        def set_a(self, val):
            self.a = val
     
        @classmethod
        def set_A(class, val):
            class.A = val
     
    A = Test
    a = Test()
    b = Test()
    a.set_a(22)
    # a.a == 22, b.a == None, et Test.A == A.A == a.A == b.A == None
    A.set_A(33)
    # a.a == 22, b.a == None, et Test.A == A.A == a.A == b.A == 33
    b.set_A(44)
    # a.a == 22, b.a == None, et Test.A == A.A == a.A == b.A == 44
    A.set_a(55)
    # Génère une erreur…

    En clair, une instance peut accéder aux variables de sa classe, mais pas l’inverse.

    Note le décorateur @classmethod sur Test.set_A, qui fait que le premier paramètre passé à cette fonction est l’objet type, et pas l’instance…

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    91
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 91
    Points : 65
    Points
    65
    Par défaut
    merci pour vos réponses.

    @tyrtamos
    je suis distrait....
    @mont29
    je voulais effectivement écrire t=Toto(). Ceci dit merci pour l'explication var de classe/d'instance.

    J'essai en fait de comprendre une erreur dans un code un peu plus long.
    J'ai écris une classe pour lire un fichier de configuration. Elle possède une méthode qui permet de recupérer un path:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    def set_particlespath(self,index):
            '''Set the path to the particles directory, in the DAPI directory'''
            #user,"Applications","ImagesTest","jp","Jpp48","13","DAPI","particules"
            print "index=None?",index
            print "self.metaphases_list",self.metaphases_list
            #print "self.metaphases_list[0]",self.metaphases_list[index]
            #self.path=os.path.join(self.wdir,self.user,self.slide,self.metaphases_list[index],self.counterstain,"particles")
            #print "self.path",self.path
            return self.path
    une sortie partielle donne:
    index=None? 0
    self.metaphases_list ['13', '14']
    la variable index vaut 0.
    Quand je décommente la ligne:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    print "self.metaphases_list[0]",self.metaphases_list[index]
    je m'attendais à avoir en sortie:
    13
    C'est à dire le premier élément de la liste self.metaphases_list. Et j'ai l'erreur:
    print "self.metaphases_list[0]",self.metaphases_list[index]
    TypeError: list indices must be integers, not NoneType
    ce qui veut dire que index=None au lieu de index=0

    Le code complet est:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    # -*- coding: utf-8 -*-
    """
    Created on Mon Sep 26 13:23:54 2011
     
    @author: claire
    """
     
    import ConfigParser as CfgP
    import os,sys,ast
    #   
    class ClassifConf():
        def __init__(self):
            self.config=CfgP.RawConfigParser()
            self.config.read('configuration.cfg')
            print self.config
            self.wdir=self.config.get('Images Path','work_dir')
            self.user=self.config.get('Images Path','user')
            self.slide=self.config.get('Images Path','slide')
            self.set_metaphaseList()
            self.path=None
            #False if no particles images saved
            self.particles=False
            self.trained=False
            #Fluo
            #self.counterstain=None
            self.set_ClassifConf()
            self.set_Fluorochromes() 
        def set_metaphaseList(self):
            '''convert the string containing the metaphases list
            stored in the config file to a list of integers'''
            tmp=self.config.get('Images Path','field_list')
            #self.metaphases_list=map(lambda x:int(x),tmp.split(','))
            self.metaphases_list=tmp.split(',')
        def set_particlespath(self,index):
            '''Set the path to the particles directory, in the DAPI directory'''
            #user,"Applications","ImagesTest","jp","Jpp48","13","DAPI","particules"
            print "index=None?",index
            print "self.metaphases_list",self.metaphases_list
            print "self.metaphases_list[0]",self.metaphases_list[index]
            #self.path=os.path.join(self.wdir,self.user,self.slide,self.metaphases_list[index],self.counterstain,"particles")
            #print "self.path",self.path
            return self.path
        def set_particles(self,path):
            '''set to true if chromosomes were segmented '''
            if os.path.isdir(path):
                self.particles=True
        def set_trained(self):
            '''set to true if chromosomes images were classified
            manually to single chr, overlapping chr, nuclei, dusts'''
            self.trained=False
        def set_ClassifConf(self):
            '''read conf param for the classif GUI:
                screen size, number of classif box their size'''
            #seen at stackoverflow.com: T2 = [map(int, x) for x in T1]
            #to convert a string to a list of tuples
            #map(lambda x: int(x), ['1', '2', '3'])
            tmpsize=self.config.get('ClassifierGUI','screen_size').split(',')
            #print tmpsize
            self.screensize=map(lambda x:int(x),tmpsize)
            self.catsize=int(self.config.get('ClassifierGUI','categories_number'))
            self.catlist=self.config.get('ClassifierGUI','categories_list') 
            tmpbox=self.config.get('ClassifierGUI','box_size').split(',')
            #print 'tmpbox',tmpbox
            self.boxsize=map(lambda x:int(x),tmpbox)
            tmpboxpos=ast.literal_eval(self.config.get('ClassifierGUI','box_position'))
            #print tmpboxpos
            self.boxpos=list(tmpboxpos)
     
        def set_Fluorochromes(self):
            '''#Fluorochromes'''
            self.counterstain=self.config.get('Fluorochromes','Counter_stain') 
            print "cs:",self.counterstain        
            self.probes=self.config.get('Fluorochromes','Probes').split(',')
    def main():
        configurator=ClassifConf()
        print type(configurator.catlist)
        print configurator.screensize[0]+1
        print configurator.boxpos
        print configurator.boxpos[0][0]+1
        print '##########'
        print configurator.counterstain
        print configurator.probes[1]
        print "meta:",configurator.metaphases_list[0]
        path=configurator.set_particlespath(0)
        print "path:",path
        configurator.set_particlespath(path)
    if __name__ == '__main__': main()
    Le fichier de configuration contient:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #read by miniChromClassif.py
    [Fluorochromes]
    Counter_stain=DAPI
    Probes=Cy3,Cy5,FITC
    [Images Path]
    work_dir=/home/claire/Applications/ImagesTest/
    user=jp
    slide=Jpp48
    field_list=13,14
    [ClassifierGUI]
    screen_size=1024,768
    categories_number=4
    categories_list=single chr,touching chr,nuclei,dusts
    box_size=200,100
    #((col,li),(col+200+30,li),...)!!
    box_position=(5,650),(235,650),(465,650),(695,650)

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    91
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 91
    Points : 65
    Points
    65
    Par défaut
    J'ai corrigé l'erreur, je ne sais trop comment ...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    import ConfigParser as CfgP
    import os,sys,ast
    #   
    class ClassifConf():
        def __init__(self):
            self.config=CfgP.RawConfigParser()
            self.config.read('configuration.cfg')
            print self.config
            self.wdir=self.config.get('Images Path','work_dir')
            self.user=self.config.get('Images Path','user')
            self.slide=self.config.get('Images Path','slide')
            self.set_metaphaseList()
            self.path=None
            #False if no particles images saved
            self.particles=False
            self.trained=False
            #Fluo
            #self.counterstain=None
            self.set_ClassifConf()
            self.set_Fluorochromes() 
        def set_metaphaseList(self):
            '''convert the string containing the metaphases list
            stored in the config file to a list of integers'''
            tmp=self.config.get('Images Path','field_list')
            #self.metaphases_list=map(lambda x:int(x),tmp.split(','))
            self.metaphases_list=tmp.split(',')
        def set_particlespath(self,index):
            '''Set the path to the particles directory, in the DAPI directory'''
            self.path=os.path.join(self.wdir,self.user,self.slide,self.metaphases_list[index],self.counterstain,"particles")
        def set_particles(self,path):
            '''set to true if chromosomes were segmented '''
            if os.path.isdir(path):
                self.particles=True
        def set_trained(self):
            '''set to true if chromosomes images were classified
            manually to single chr, overlapping chr, nuclei, dusts'''
            self.trained=False
        def set_ClassifConf(self):
            '''read conf param for the classif GUI:
                screen size, number of classif box their size'''
            #seen at stackoverflow.com: T2 = [map(int, x) for x in T1]
            #to convert a string to a list of tuples
            #map(lambda x: int(x), ['1', '2', '3'])
            tmpsize=self.config.get('ClassifierGUI','screen_size').split(',')
            #print tmpsize
            self.screensize=map(lambda x:int(x),tmpsize)
            self.catsize=int(self.config.get('ClassifierGUI','categories_number'))
            self.catlist=self.config.get('ClassifierGUI','categories_list') 
            tmpbox=self.config.get('ClassifierGUI','box_size').split(',')
            #print 'tmpbox',tmpbox
            self.boxsize=map(lambda x:int(x),tmpbox)
            tmpboxpos=ast.literal_eval(self.config.get('ClassifierGUI','box_position'))
            #print tmpboxpos
            self.boxpos=list(tmpboxpos)
     
        def set_Fluorochromes(self):
            '''#Fluorochromes'''
            self.counterstain=self.config.get('Fluorochromes','Counter_stain') 
            #print "cs:",self.counterstain        
            self.probes=self.config.get('Fluorochromes','Probes').split(',')
    def main():
        configurator=ClassifConf()
        configurator.set_particlespath(1)
        print "path:",configurator.path
        print type(configurator.path)
    if __name__ == '__main__': main()
    Avec le même fichier de config, la sortie est:
    <ConfigParser.RawConfigParser instance at 0x91e6aec>
    path: /home/claire/Applications/ImagesTest/jp/Jpp48/14/DAPI/particles
    <type 'str'>

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 4
    Dernier message: 17/05/2009, 23h29
  2. Modifier une variable d'instance par une autre
    Par alvanoto dans le forum Débuter avec Java
    Réponses: 4
    Dernier message: 30/03/2009, 02h13
  3. [Smarty] Attribuer une class en fonction d'un résultat avec une variable
    Par kitten13 dans le forum Bibliothèques et frameworks
    Réponses: 1
    Dernier message: 25/09/2008, 21h03
  4. STL Problème avec une liste d'instances de class
    Par BruceBoc dans le forum SL & STL
    Réponses: 12
    Dernier message: 16/02/2007, 15h12
  5. probleme d'espace avec une "var" :-(
    Par weldoo dans le forum Delphi
    Réponses: 9
    Dernier message: 30/07/2006, 21h41

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo