#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0

    Cool Class object does not work as expected.


    As this is my first post, I should say hello first.
    However, I am facing a problem:
    Code:
    class products:
    	def __init__(self, name, price):
    		self.name = name
    		self.price = price
    	def prolist(self):
    		for a, v in enumerate(self.name):
    			return str(a+1), v
    I have defined this class, but when I try to:
    Code:
    pr1 = products('foo', 123)
    I get this:
    Code:
    <__main__.products instance at 0x7f79091df6c8>
    Why does that happen? And how can I make it return strings instead?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    If you instantiate a class, you get an instance of that class...I'm not sure what's the issue?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    479
    Rep Power
    33
    You do not call the function prolist() so it is never executed. Note that the function issues a return after the first pass through the for loop so only the first iteration/value is returned. Also, try to follow the Python style guide and set your editor to use spaces instead of tabs to make your code more readable.
    Code:
    class Products:
        def __init__(self, name, price):
            self.name = name
            self.price = price
            print self.prolist()
    
        def prolist(self):
            for a, v in enumerate(self.name):
                return str(a+1), v
    
    pr1 = products('foo', 123)
    print "2nd call", pr1.prolist()
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    As the others have already remarked, your expectations are faulty. Replace the __repr__ method to get a behavior different from the report of object type.
    Code:
    class products:
        def __init__(self, name, price):
            self.name = name
            self.price = price
    
        def prolist(self):
            return list((str(a), v) for (a,v,) in enumerate(self.name))
    
        def __repr__(self):
            return str(self.prolist())
    
    pr1 = products('abc',345)
    print(pr1)
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo