Class question

This is the place for queries that don't fit in any of the other categories.

Class question

Postby Joralf » Wed Jun 11, 2014 10:54 am

Hi guys,

I'm a bit new to the concept of OOP, but slightly I'm getting there. I do however have a question.

Suppose we have a class called Helloworld where you can input a string that is supposed to read a message to the world. The string is displayed with a function displaystring inside the class Helloworld. Nothing to fancy.

However, when I define an object msg1 containing the message I want to send to the world I'm unable to display it with displaystring without explicitly putting the message in the functioncall. Why is this? I already assigned my message to msg1 through Helloworld(message). By calling msg1.displaystring one would assume it would display the message which object msg1 contains. What am I doing wrong here?

Code:
Code: Select all
#! /usr/bin/env python3.4

class Helloworld:

   def __init__(self,string):
      self.string = string

   def displaystring(self,string):
      return (string)

message = "Hi there folks!"

msg1 = Helloworld(message)


print (msg1.displaystring)
print (msg1.displaystring(message))


Output:
<bound method Helloworld.displaystring of <__main__.Helloworld object at 0x7fba059cb860>>
Hi there folks!



Added note: By using msg1.displaystring(message) you're actually calling for print(Helloworld(message).displaystring(message)). I find it strange I'd have to insert the message I want to display twice.
Joralf
 
Posts: 4
Joined: Wed Jun 11, 2014 10:42 am

Re: Class question

Postby Mekire » Wed Jun 11, 2014 12:07 pm

The variable string in your displaystring method has nothing to do with the string you passed to your __init__ when you created your instance.

You presumably meant this:
Code: Select all
#! /usr/bin/env python3.4

class Helloworld:
   def __init__(self,string):
      self.string = string

   def displaystring(self):
      return self.string


message = "Hi there folks!"
msg1 = Helloworld(message)
print(msg1.displaystring)
print(msg1.displaystring())

-Mek
User avatar
Mekire
 
Posts: 1031
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Class question

Postby Joralf » Wed Jun 11, 2014 12:12 pm

Right! So for methods that use the variable given when creating an object one should use self.variable and not ask for a variable when calling the method..

Should have seen that myself. Thanks!
Joralf
 
Posts: 4
Joined: Wed Jun 11, 2014 10:42 am


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 4 guests