3 Replies - 587 Views - Last Post: 23 May 2012 - 05:59 AM Rate Topic: -----

#1 monster92  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 30
  • Joined: 10-May 11

What's the best way to understand classes and the concept of '

Posted 23 May 2012 - 02:13 AM

I'm currently having a real issue with understanding the concept of self in class. Below is some of the code I am using to try and help me understand


class TheThing(object):	              

	def __init__(self):					
		self.number = 0

	def some_function(self):
		print "I got called"

	def add_me_up(self, more):
		self.number += more
		return self.number

a = TheThing()
b = TheThing()

a.some_function()
b.some_function()

print a.add_me_up(50)
print b.add_me_up(20)

print a.number
print b.number

class TheMultiplier(object):

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

    def do_it(self, m):
        return m * self.base

x = TheMultiplier(a.number)
print x.do_it(b.number)



The most complicated part I think is

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


I don't understand why self.base = base. I am assuming base is a variable coming from TheThing class. However, I am not sure why this assignment is there. What is its purpose? I have been reading that self doesn't have a value the programming can change so in my mind I have base = base. Without this assignment the code does not work. Why?

To confirm, __init__ allows for internal variables. Internal variables cannot be shown outside of the function, right? How does self come into this?

Thank you so much for your time and effort :)

Is This A Good Question/Topic? 0
  • +

Replies To: What's the best way to understand classes and the concept of '

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,203
  • Joined: 21-June 11

Re: What's the best way to understand classes and the concept of '

Posted 23 May 2012 - 02:29 AM

__init__ is a function that takes two parameters. The first parameter is called self (but you could call it anything else if you want), the second is called base. The body of the function sets the base attribute of self to the value of the base parameter. This is not at all the same thing as base = base, which wouldn't touch self at all.

When you do TheMultiplier(something) in your code, a new TheMultiplier object will be created and __init__ will be called with that object as the first argument and something as the second argument. So by doing self.base = base, __init__ creates an attribute called base on that object and sets its value to something. If that line wasn't in __init__, no such attribute would exist on that object.

Quote

To confirm, __init__ allows for internal variables. Internal variables cannot be shown outside of the function, right?


You mean local variables? Yes, any function can have local variables and yes, they're not accessible outside of the function.

Quote

How does self come into this?


self is a parameter and as such it is local to the function. So if you set self to a new value inside the function (i.e. you do self = foo), that change won't be visible outside of the function. However if you change self in ways other than reassigning it (for example by settings its attributes as is the case he), those changes will be visible outside of the function.

This post has been edited by sepp2k: 23 May 2012 - 02:36 AM

Was This Post Helpful? 0
  • +
  • -

#3 Cenron  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 13
  • Joined: 23-May 12

Re: What's the best way to understand classes and the concept of '

Posted 23 May 2012 - 05:26 AM

When I first started with object oriented programming I had a very hard time conceptualizing objects but once you get them they are the best thing since slice bread.

Ill try and explain it in a way that hopefully make sense. Think of an object as a real life object like for example an Apple

This apple has certain characteristics for example:
Size: 5inch diameter
Color: Red
Weight: 5oz

These characteristics are set when the tree creates or "Constructs" this apple. So "__init__" is called during the construction phase of the apple and the characteristics are set:

class Apple :
	# Class internally has properties:
	# Size
	# Color
	# Weight

	# Set the initial properties
	def __init__( self ) :
		# These properties get created when they are set.
		self.Size  = 5in 
		self.Color = Red
		self.Weight = 5oz
		
	# Get the color of the apple.
	def GetColor( self ) :
		return self.Color
		
	# Get the size of the apple.
	def GetSize( self ) :
		return self.Size
		
	# Get the Weight of the apple.
	def GetWeight( self ) :
		return self.Weight
		
	



So this is where the self pointer comes in, note in other languages this could be called this for example in c++.

So now we have one (1) apple, but lets say we want another apple and this apple is different:

class Apple :
	# Class internally has properties:
	# Size
	# Color
	# Weight

	# Set the initial properties
	def __init__( self ) :
		# These properties get created when they are set.
		self.Size  = 10in # Notice the change
		self.Color = Green # Notice the change
		self.Weight = 25oz # Notice the change
		
	# Get the color of the apple.
	def GetColor( self ) :
		return self.Color
		
	# Get the size of the apple.
	def GetSize( self ) :
		return self.Size
		
	# Get the Weight of the apple.
	def GetWeight( self ) :
		return self.Weight
		
	



Now this new apple is MUCH bigger then the previous apple and its also green, but its still and apple and has the same properties, but these properties are set during its creation. Also the properties of the green apple don't effect the red apple.

Thats what self does, it tells python that this object internally has these properties and is not effected by any other apple that might be around.

Also one thing you will notice is most programmers are lazy and don't want to keep writing the same code over and over again. So because we know that all apples will have the same characteristics so lets make this class more generic and let the tree set these characteristics at the time of the creation of the apple.

class Apple :
	# Class internally has properties:
	# Size
	# Color
	# Weight

	# Set the initial properties
	def __init__( self, apple_size, apple_color, apple_weight ) :
		# These properties get created when they are set.
		self.Size  = apple_size 
		self.Color = apple_color
		self.Weight = apple_weight
		
	# Get the color of the apple.
	def GetColor( self ) :
		return self.Color
		
	# Get the size of the apple.
	def GetSize( self ) :
		return self.Size
		
	# Get the Weight of the apple.
	def GetWeight( self ) :
		return self.Weight
		
#### End of Apple Class

# Start of our TREE #

# In our tree create our red apple.
# and set the characteristcs during this creation.
red_apple = Apple( 5in, red, 5oz )
print red_apple.GetColor() # Prints Red
print red_apple.GetSize() # Prints 5in
print red_apple.GetWeight() # Prints 5oz

# The tree creates another apple, but this
# time its green and HUGE!!
green_apple = Apple( 10in, green, 25oz )
print red_apple.GetColor() # Prints green
print red_apple.GetSize() # Prints 10in
print red_apple.GetWeight() # Prints 25oz




So in short when you first create a class like our tree creates an apple, PYTHON internally first calls def __init__ function so you have a chance to set your variables.

And then you use self because you need to let PYTHON know that you are wanting to only set the variable for this apple and not the others.

One more thing is the reason the first parameter is self is because PYTHON needs to know where these characteristics are stored in memory, in other programming languages such as C++ you don't have to define the first parameter as self/this because the compiler automatically sets self/this as the first parameter when it converts it to machine code. The people that created PYTHON decided they want you to pass self into your class instead of it being assumed by the interpreter.

I hope this made it a little easier to understand the objects and what self and __init__ are.

P.S. Please don't mind any typos its 5:30 am here and I am typing this with one eye open. Good Night!!!
Was This Post Helpful? 0
  • +
  • -

#4 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,203
  • Joined: 21-June 11

Re: What's the best way to understand classes and the concept of '

Posted 23 May 2012 - 05:59 AM

View PostCenron, on 23 May 2012 - 02:26 PM, said:

So this is where the self pointer comes in, note in other languages this could be called this for example in c++.


In Python it can be called "this" as well. Or foobar. It's a variable name - you can call it anything you want. It's simply convention to call it self.

Quote

And then you use self because you need to let PYTHON know that you are wanting to only set the variable for this apple and not the others.


No, you need self because otherwise you'd be operating on local variables. Doing foo = bar instead of self.foo = bar inside an Apple method wouldn't set the attribute foo for all apple objects. It would set a local variable foo that would go out of scope as soon as the method finishes.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1