Some Minor questions on Class and Functions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Mar 20 00:39:49 EDT 2011


On Sat, 19 Mar 2011 16:57:58 -0700, joy99 wrote:

> Dear Group,
> 
> I am trying to pose two small questions.
> 
> 1) I am using Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.
> 1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()"
> for more information, on WINXP SP2.
> 
> As I am writing a code for class like the following: IDLE 2.6.5
>>>> class Message:
> 	def __init__(self,str1):
> 		self.text="MY NAME"
> 	def printmessage(self):
> 		print self.text
> 
> It works fine as can be seen in the result:
>>>> x1=Message(1)
>>>> x1.printmessage()
> MY NAME
> 
> Now if I open a new window and write the same code value in printmessage
> is giving arbitrary or no values.

The description of your problem does not make sense to me. Can you show 
an example?



> 2) Suppose I have a code:
> 
>>>> def hello():
> 	print "HELLO SIR"
> 
> Can I write another function where I can call the value of this function
> or manipulate it?

No. The string "HELLO SIR" is a local variable to the hello() function. 
You cannot modify it from outside that function. Since your hello() 
function prints the result, instead of returning it, another function 
cannot capture it either.

Perhaps what you want is something like this:


def hello(message="HELLO SIR"):
    return message


Now you can call the function, and print the result:

print hello()

If you want to capture the return value, you can:

result = hello()
print result.lower()

If you want to change the message used, you can pass it to the function 
as an argument:

hello("Greetings and salutations!")



Hope this helps,



-- 
Steven



More information about the Python-list mailing list