python class problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pythonadict
    New Member
    • May 2011
    • 2

    python class problem

    I have a problem w python class, I come form java and its so diferent, lets show problem

    Code:
     
    
    class Client:  #define the class
       
      def __init__(self,name):
        self.name_client=name
    
    
    if __name__=="__main__": #starting point
    
    coco = raw_input("Name of the client")
    coco = Client(coco)
    print coco.name_client
    print coco

    What python prints to me is

    Name of the client

    # lets say we input Jhon

    Jhon
    <__main__.Clien te instance at 0x01EEFF58>


    What the hell its <__main__.Clien te instance at 0x01EEFF58> ?? I dont undestand why puts that value and not Jhon.

    Need help w this please
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Overload repr() to display whatever you want.
    Code:
    >>> class Client:
    ... 	def __init__(self, name):
    ... 		self.client_name = name
    ... 	def __repr__(self):
    ... 		return self.client_name
    ... 	
    >>> name = raw_input("Enter name")
    >>> name
    'Bill'
    >>> client = Client(name)
    >>> client
    Bill
    >>>

    Comment

    • pythonadict
      New Member
      • May 2011
      • 2

      #3
      Well what I really want is make a class, that when I call it, makes an instance of class Client,

      w the name the user inputs w the keyboard like

      x=Raw_input("En ter teh name")
      >> Bill
      then program makes
      Bill = Cliente("Bill")
      and adds the Client instance name to a list, so I can remember or lsit all theclients

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        You are using the same variable for two different things, the name of the client and the class instance.
        Code:
        coco = raw_input("Name of the client")
        class_instance = Client(coco)
        print class_instance.client_name
        print coco
        To use a list or dictionary:
        Code:
        class Client:
            def __init__(self, name):
                self.client_name = name
                self.a_number = 1
        
        if __name__=="__main__": #starting point
         
            class_instance_list = []
            for name in ["Bill", "Sue", "Tom"]:
                class_instance = Client(name)
                class_instance_list.append(class_instance)
        
            print len(class_instance_list), "clients added\n"
            for class_instance in class_instance_list:
                print class_instance.client_name, class_instance.a_number

        Comment

        Working...