Pokémon X and Y Fan Community
January 27, 2021, 02:05:07 pm
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  Home Help Search Arcade Gallery SHOUTBOX Staff List Calendar Members Login Register  

Programming Thread

Pages: 1 ... 8 9 [10] 11 12
  Send this topic  |  Print  
Author Topic: Programming Thread  (Read 1045 times)
Magical Misdreavus

Level: 5
Offline Offline

Posts: 126

View Profile WWW
Badges: (View All)
« Reply #135 on: May 16, 2013, 02:15:42 am »

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

This is the constructor for the class, consider it a special function (method) if you will. Everytime an object is created from that class then the constructor will be called. You'll notice the arguments 'self' and 'lyrics'. The self argument is a little complicated because it works in a different way than all the other arguments. (I'll come back to it later)
For 'lyrics', that's basically the variable that will hold any value you pass into your class when you create it. All arguments after 'self' are entirely optional and up to the programmer.

class Car():
    colour = "Unknown"
    def __init__(self, col):

car = Car("Red")
Will output "Red". If you were to change the print(col) to print(colour), then we'd get an error because the variable 'colour' is not in the function (__init__). To access it you'd have to use self.colour so, print(self.colour) would print out "unknown".
Setting the variable works in the same way:

class Car():
    colour = "Unknown"
    def __init__(self, col):
        self.colour = col

    def get_color(self):

car = Car("Red")

Each function in a class MUST have 'self' as a parameter. This is because Python passes an extra value behind the scenes, which goes into the self variable. It doesn't have to be called 'self' either, you can rename it to what you like. It'll still work in the same way.

As for this line:
class Song(object):
(object) is forcing whatever you pass into __init__ as an argument (lyrics) to be an object data type. That's all really. Try setting (object) to (int) and you'll see that you'll only be able to pass ints into lyrics.
Report Spam   Logged

Pages: 1 ... 8 9 [10] 11 12
  Send this topic  |  Print  
Jump to:  

Powered by EzPortal
Bookmark this site! | Upgrade This Forum
Free SMF Hosting - Create your own Forum

Powered by SMF | SMF © 2016, Simple Machines
Privacy Policy
Page created in 0.095 seconds with 9 queries.