Advertisement

How to use Class?and what is return?

Started by November 16, 2013 12:01 PM
7 comments, last by Hraefn 11 years, 2 months ago

Hi everyone i have a question about how to use a class so i make this script:

>>> class className:
def createName(self,name):
self.name=name
def displayName(self):
return self.name
def saying(self):
print 'Hello %s' % self.name

>>> first=className

>>> first.createName('X')

I learn this from a tutorial but i have an error:

Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
first.createName('X')
TypeError: unbound method createName() must be called with className instance as first argument (got str instance instead)

the tutorial i watched is using 2.6 and i'm using 2.7 also what is the difference between return and print in def

and why i need to use (self,name) instead of only (self)

Thank you very much

  1. Please give us the link which tutorial you watched
  2. the difference between return print and def are:
    1. def say you want define a new function
    2. return say you want return something from a function
    3. print is a function
  3. to the last one i can only say you need that self only in the definition of a class in python from what i know...
  4. You forgot to use '()' in the end of className at the line where you create this object!
    1. first = className()
    2. otherwise you would not call the ctor(constructor)

http://docs.python.org/2/tutorial/classes.html

Advertisement

To put it really simply, return sets the value of the function, while print simply prints to the screen. In very simple functions, they can appear to be the same thing because of the way the Python interpreter works, but they're very different. For example, compare these two functions.


def foo_return():
 return 5
 return 3

def foo_print():
 print 5
 print 3

foo_return()
foo_print()

v1 = foo_return()
v2 = foo_print()

Call foo_return() and you will get "5", because the interpreter itself prints return values. Call foo_print() and you'll see 5 followed by 3. Likewise, v1 will be equal to 5. v2 won't be equal to anything, because you didn't return anything. However, since you called the function, you'll print the two values again. So if you run the above in python as-is, you'll see something like:


5
5
3
5
3

As far as the reason you need "self" in python, it's a bit complicated, but it basically chalks down to the way classes are built under the hood. You don't really need to worry about it as long as you make sure to include it.

  1. Please give us the link which tutorial you watched
  2. the difference between return print and def are:
    1. def say you want define a new function
    2. return say you want return something from a function
    3. print is a function
  3. to the last one i can only say you need that self only in the definition of a class in python from what i know...
  4. You forgot to use '()' in the end of className at the line where you create this object!
    1. first = className()
    2. otherwise you would not call the ctor(constructor)

http://docs.python.org/2/tutorial/classes.html

i know where is my mistake i forgot to use () in first = className() thank you very muchbiggrin.png

To put it really simply, return sets the value of the function, while print simply prints to the screen. In very simple functions, they can appear to be the same thing because of the way the Python interpreter works, but they're very different. For example, compare these two functions.




def foo_return():
 return 5
 return 3

def foo_print():
 print 5
 print 3

foo_return()
foo_print()

v1 = foo_return()
v2 = foo_print()

Call foo_return() and you will get "5", because the interpreter itself prints return values. Call foo_print() and you'll see 5 followed by 3. Likewise, v1 will be equal to 5. v2 won't be equal to anything, because you didn't return anything. However, since you called the function, you'll print the two values again. So if you run the above in python as-is, you'll see something like:




5
5
3
5
3

As far as the reason you need "self" in python, it's a bit complicated, but it basically chalks down to the way classes are built under the hood. You don't really need to worry about it as long as you make sure to include it.

Thank you for the explaination but why i can use (self,name) and not only (self)smile.png


print 'Hello %s' % self.name

use


print('Hello %s' % self.name)

for Python 2 and 3 versions compatibility

also you can use


class className:
    def __init__(self,name):
        self.name=name
........

cls_inst = className('X')
cls_inst.saying()
Advertisement

It took me a while to understand classes but I will see if I can help.

A class is a way to classify variables. An apple is a type of fruit. Apple is the variable, and fruit is the class. In python an apple is made a fruit this way:


apple = Fruit()

However, an orange is a fruit as well. So we can also make it a fruit:


orange = Fruit()

Now, all fruit have certain characteristics. They all have a taste. They also have a color. You can also classify them by size.

Taste, color, and size would be variables that are a part of your fruit class, so that you could type:


print (orange.color) 

And you could get the color of the orange.

Whenever you make a variable a part of a class, you are making it an instance of the class. You are also making it an object (because now it has characteristics). The apple is one instance and the orange is another instance.

The self.name is nothing special really other than the fact that we want to be able to type apple.name to get the apple's name rather than just name. The name of your object will be substituted for the self. So you can read the self as apple.name or orange.name

They have to make self.name = name so that they can use name as an argument. That means that wherever the word name is in the class, switch it out for something else.

>>> class className:
def createName(self,name):
self.name=name
def displayName(self):
return self.name
def saying(self):
print 'Hello %s' % self.name

>>> first=className

>>> first.createName('X')

As for return. It works just like return does for functions.

If you had a function called Add(x,y) that adds two numbers x and y You would want the function to add the two numbers and then return the answer.


def Add(x,y):
answer = x + y
return answer

So if you type

Add(3,4)

This function should return 7.

Without the return part, the function would add, but it wouldn't output an answer.

For a more detailed explanation of OOP (Object Oriented Programming) check out my tutorial:

http://forum.maratis3d.com/viewtopic.php?id=839

They call me the Tutorial Doctor.

Larger programs usually model aspects of the program's domain. For a business application, the domain might be the business processes of a given company. For a RPG game, the domain is the fantasy world in which the events take place. For Pac-Man, the domain is the flat, 2D maze and the Ghost, pills and fruit that inhabit the world with the circular hero.

Object oriented languages are a popular way of modelling the domain. In this way of thinking, we want each interesting object in the domain to correspond to an object or set of objects in our program. An object could be a simple concrete thing, such as an enemy, a gun or a cactus. It can be more abstract, such as an unit or build order in an RTS game or a tile in a tile-based game.

We will quickly note that many of the objects come in groups, and are similar. For example, we will have different types of enemies, different guns or different orders we can give units. In an object oriented program, these groups are modelled as classes, and the individual objects are so-called instances. In an object oriented Pac-Man, there might be a Ghost class, and four instances for Inky, Binky, Pinky and Clyde. The fundamental idea is that you can write some code that will work with any Ghost, and sometime later in the program that code could be used on any particular instance of the Ghost class that might be around, without caring which particular ghost was used.

Most computer programs make a profound distinction between code and data. Most programming languages define the program code in a number of functions or procedures. The data is the contents of the variables in the program. At the time object orientation was being introduced, the popular languages at the time had a very simple mapping, code was represented as functions or procedures that acted on data, which was stored in data structures. Any function or procedure could typically change any data it wanted in the data structure. It could sometimes be quite difficult to track down the code that changed a variable to an unexpected or bad state in a large program.

Object orientated languages usually try and put the code (or behaviour) and data of an object together, often giving the programmer the option to hide certain bits of behaviour and data from the rest of the program. The belief is that an object should mange it's own data, and should be responsible for enforcing some rules about it's data. For instance, a Ghost in Pac-Man can either be alive (if you pardon the expression, I mean chasing Pac-Man), or be flashing blue, or be "dead" (returning to their pen). An object oriented purist would insist that the Ghost class be written so that it would not be possible to put the Ghost into an invalid state, or here multiple states. So any data that represents this state would be preferably hidden from the program, and the Ghost would only expose the methods necessary for the program to inform the Ghost of events such as Pac-Man eating a power pill, Pac-Man touching the Ghost, and the Ghost entering the pen. Then the ghost could decide to change it's state in response to these events.

Unfortunately, demonstrating the value of object orientation is challenging to a beginner, as the kind of complex program where this becomes an issue would be very difficult to explain. Generally speaking, the practical value of such rules is only evident to programmers when they start to build medium sized projects that pass a certain amount of complexity.



It took me a while to understand classes but I will see if I can help.

[...]

For a more detailed explanation of OOP (Object Oriented Programming) check out my tutorial:

http://forum.maratis3d.com/viewtopic.php?id=839

Thank you for you help and I will read all the tutorial biggrin.png



Larger programs usually model aspects of the program's domain. For a business application, the domain might be the business processes of a given company. For a RPG game, the domain is the fantasy world in which the events take place. For Pac-Man, the domain is the flat, 2D maze and the Ghost, pills and fruit that inhabit the world with the circular hero.

[...]

Unfortunately, demonstrating the value of object orientation is challenging to a beginner, as the kind of complex program where this becomes an issue would be very difficult to explain. Generally speaking, the practical value of such rules is only evident to programmers when they start to build medium sized projects that pass a certain amount of complexity.

Thanks for that explanation I still will keep practice thank you so muchsmile.png

This topic is closed to new replies.

Advertisement