Re: Python crash course

2015-10-03 Thread AudioGames . net Forum — Developers room : frastlin via Audiogames-reflector


  


Re: Python crash course

classesA class is like a template. You say "I want to make a cat" and you create a cat class:class Cat(object):    passNow you have a class for a cat. Next we need to figure out what a cat has and what it does. A cat has an age, so we can identify an age. It also has a name, so we can name it. It also purrs and it catches mice.So lets create this template for a class with age, name, purr and catch mice.We are going to use something called an init function. init is short for initialize and is run every time you create an object. We can pass the init function arguments, so we will do that. We can identify the attributes of the cat class by using the "self" keyword. So in the init function we pass in some variables as arguments and we set the self.variables to equal the passed in variables.Cat class:class Cat(object):    def __init__(self, name, age):      
 bsp; self.name = name        self.age = age    def purr(self):        print("purr... purr...")    def catch_mice(self):        print("%s goes and stocks a hapless mouse and at the last moment the cat pounces on it! Yummm..." % self.name)OK, so now we have a cat class with a self.age and a self.name. This Cat class is not a cat, it is all cats, so we need to create a cat that we can pet and play with:midnight = Cat("midnight", 3)Now we have a cat named midnight. Lets look at his age:print(midnight.age)3This means that when we were creating the Cat class "self" just identified this nebulous, unidentified object. We needed to actually "create" a cat by saying "I am god, let there be midnight that is a Cat!" Now if you needed to change something to only midnight, you woul
 d need to use midnight rather than self. Otherwise you would change all cats.For example:midnight.age = 5print(midnight.age)5So we have midnight who is an object of Cat. What else can he do? He can purr! Lets watch him purr:midnight.purr()purr... purr...Awesome! Now your midnight cat purrs and has an age. He also has a catch_mice function he can do as well! But what happens if we try and make our midnight bark? We will get an error that midnight doesn't have that function. We can make it though:def bark():    print("Midnight expands his neck into a veritably massive lump of flesh and lets out the strangest woof ever!")midnight.bark = barkSo now we have, in a sense, trained our midnight to bark. Lets say we would like another cat, lets create one:frisky = Cat("Frisky", 7)Now we have 2 cats, frisky and midnight. Lets check that they are both cats:prin
 t(frisky.age)7print(midnight.age)5frisky.purr()purr... purr...midnight.purr()purr... purr...midnight.bark()Midnight expands his neck into a veritably massive lump of flesh and lets out the strangest woof ever!frisky.bark()ERROR ERROR Cats can't bark!Frisky has all the properties of a cat, but not the special property we gave to midnight. we would have to give him special training in order to have him bark.This is a class. It is really simple, so sorry for taking such a long post to explain it. A class is just a template, like a document or email. You create the class which has fields and properties that you specify (an email has subject, to and body for the properties and send, reply and forward for the functions). Then you create an instance of that object. midnight = Cat("Midnight", 3). When we create the object, our __init__ function is run, setting the self.name as name and th
 e self.age as age. Then it replaces self with midnight.That's all, when you create midnight, you are saving that specific template under the name of midnight. It is an instance of the template Cat, but is it THE template Cat? no! midnight is just 1 Cat.

URL: http://forum.audiogames.net/viewtopic.php?pid=233707#p233707




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector

Re: Python crash course

2015-10-03 Thread AudioGames . net Forum — Developers room : dhruv via Audiogames-reflector


  


Re: Python crash course

 string formatting There are 2 ways to format a string in python. String formatting essentially means that you replace some words in the string where denoted. Strings are like templates and you fill them with stuff.Example 1. string formatting with %s:mystring = "hi, %s! how are you doing?"
print mystring%("dhruv")Essentially, you denote where words should be replaced in the string with the %s tag. This can do a lot more crazy stuff, like digits and floating point numbers and whatnot, so googling might be helpful.example 2. string formatting with .format:mystring = "Hi, {}! how are you doing?"
print mystring.format("bob")In this example, we use {} to denote the place where stuff should be put. .format and %s are pretty much functionally equivalent, so use what you're more comfortable with. string concatenation Many people will probably be familiar with this. In the first post, cae_jones showed us this.The difference between string formatting and string concatenation is that string "templates" are reusable. In string formatting, you have a template you can plug your variables in, whereas in string concatenation you just add strings and they're not reusable. Example below:example 3. string concatenation:myname = "rambo"
print "hi", + myname+"!"Essentially, you add (concatenate) strings together to make a new string.

URL: http://forum.audiogames.net/viewtopic.php?pid=233728#p233728




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector

Re: Python crash course

2015-10-03 Thread AudioGames . net Forum — Developers room : Ethin via Audiogames-reflector


  


Re: Python crash course

Input and OutputIO (or I/O) (input/output) is the concept of reading data (the "input") from a file or stream and sending the data to a destination (the "output"). IO can be done in many different ways. In this tutorial, we'll cover IO using the print statement, input() function call, and IO using files.Using print to send output to a file or streamIn Python 3.x, the print statement's syntax looks like this:print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)You will notice several strange things about the syntax of this functions. The *objects parameter might look out of place because from what I can tell, it has not been referenced. The * operator in a function parameter list means that the rest of the parameter list is infinite. Basically, print() could take an indefinite number of arguments.The sep=' ' parameter is the separator between parameters. This means that after each parameter that is not a parameter that is sep, end, file, or flush, a space is placed. This can be changed to anything you like.The end='\n' parameter is the character (or characters) that is or are placed when the statement ends. By default, a \n (newline) is placed, causing the operating system to push up all the text previously entered and create an empty space below the text at the bottom of the screen for the cursor to be placed. After that's done, the cursor is set back at the beginning of the empty space created on the screen and is ready for more input.the file=sys.stdout parameter is the stream or file (or location) for the output to be sent. This means that the print function could be technically be used to print data to files, although the file operations (covered later in this post) is recommended, as it is quicker and more efficient.The flush=false parameter indicates if all data should be placed into a buffer, and then sent to the location specified in the file parameter or immediately sent to the location specified in the file parameter without buffering it. Usually, this parameter is set to false because buffering allows a memory space to be created for the text to be sent to allow formatting and string concatenation to be completed. If set to true, the entire string will be sent, which may or may not cause errors in the string sent.An example print statement would be as follows:print ("Hello world!")An example print statement using separators and end parameter definitions would be as follows:print ("Hello world!", sep="\0", end="\n")In this statement, the system sends the null character, \0, as the separator, and sends a newline (\n) as an ending line terminator.In python 2.x, the print statement is as follows:print(*objects, sep=' ', end='\n', file=sys.stdout)As you can see, there is no flush parameter, forcing input to always be buffered.Reading and writing to filesReading and writing to files is similar to using standard IO. In this tutorial, I'll use open() to write to files, as it allows one of the cleanest methods of writing to and reading from files.The syntax for open() is as follows:open():open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)Open() opens file and returns a corresponding file object. If the file cannot be opened, an OSError is raised.file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:'r'open for reading (default)'w'open for writing, truncating the file first'x'open for exclusive creation, failing if the file already exists'a'open for writing, appending to the end of the file if it exists'b'binary mode't'text mode (default)'+'open a disk file for updating (reading and writing)'U'universal newlines mode (deprecated)The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.As mentioned in the Overview in the Python documentation, Python distinguishes between binary and text I/O. Files opene

Re: Python crash course

2015-10-02 Thread AudioGames . net Forum — Developers room : momo7807 via Audiogames-reflector


  


Re: Python crash course

Hi allThis is another subject.I'm wondering, why many audiogame developers are use python 2.7.10? The latest version is python 3.5.0. Is there any technical reasons? Or python 2.7.10 is better than the latest python?Thanks

URL: http://forum.audiogames.net/viewtopic.php?pid=233583#p233583




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector

Re: Python crash course

2015-10-02 Thread AudioGames . net Forum — Developers room : CAE_Jones via Audiogames-reflector


  


Re: Python crash course

A word on Dependency Scavenger Hunts: I don't even remember what dependencies different packages require, only that some require more than others. They are usually either in the same place where you found the package in the first place, or can be found at pypi.python.org or by googling the package name.(In this post, I'll put code in blockquotes, so it's easier to jump in/out of.)Oh, and if you want to run a program from an external .py file (notepad *.py is how I create them), import it, like so:import my_moduleHere's an excerpt from my attempt at giving Pygame easier 2D audio (will explain afterward):import math


def convert(pan=0.0, volume=0.0):
 v = ((volume+50.0)/50.0)
 if v<0.0 :
  v=0.0
 elif v>1.0 :
  v=1.0
 pan/=10.0 # or 100.0, I forget which BGT uses.
 if pan<-1.0 :
  pan=-1.0
 elif pan>1.0 :
  pan=1.0
 
 vl = v if pan<=0.0 else v*(1.0-pan)
 vr = v if pan>=0.0 else v*(1.0+pan)
 return (vl, vr)Explanation:To play sound using pygame, one must setup the mixer, get a sound pointing to the correct file, then invoke its play method.To adjust the volume and balance, however, we work with the channel that ultimately plays the sound.(It's something of a mess. Hence, everyone trying to come up with something better.)For example, this should play a sound in the right speaker:import pygame
from os.path import normpath as np

pygame.mixer.init()
my_sound=pygame.mixer.Sound(np("c:\\windows\\media\\ding.wav"))
my_channel=my_sound.play()
my_channel.set_volume(0.0, 1.0)Meh, not impressive enough.Box2DSo, here's a Box2D example. To run it, you'll need my port of Philip_bennefall's sound_pool: https://www.sendspace.com/file/h0m7tyJust to note, it is kinda monstrous to just read without having looked into Box2D enough to understand what half the stuff does. I basically use this tutorial as my primary reference:http://www.iforce2d.net/b2dtut/The point of this example is to have a ball drop onto a box, then bounce it.from Box2D import *
import pygame
import os.path
from sound_pool import *

pygame.mixer.pre_init()
pygame.mixer.init()

world=b2World(b2Vec2(0, -10), True)
true=True
false=False
none=None
null=None

statdef=b2BodyDef()
statdef.type=b2_staticBody
statdef.position.Set(10, 0)
statbod=world.CreateBody(statdef)
box=b2PolygonShape()
box.SetAsBox(100, 1)
fixdef=b2FixtureDef()
fixdef.shape=box
fixdef.density=1
fix=statbod.CreateFixture(fixdef)

balldef=b2BodyDef()
balldef.position.Set(10, 10)
balldef.type=b2_dynamicBody
ball=world.CreateBody(balldef)
circle=b2CircleShape()
circle.m_radius=1
circdef=b2FixtureDef()
circdef.shape=circle
circdef.density=1
circfix=ball.CreateFixture(circdef)
circfix.restitution=0.25
circfix.friction=0.5

snd=os.path.normpath("c:\\users\\cae\\aviewer\\sounds\\red.wav")
pool=sound_pool()
slot=pool.play_2d(snd, 0, 0, ball.position.x, ball.position.y, True)

frame=0

class CL(b2ContactListener) :
def BeginContact(this, contact) :

print "Begin Contact..." + str(frame)
pool.play_stationary("ball.wav", False)


def EndContact(this, contact) :
print "End contact. " + str(frame)



cl=CL()
world.contactListener=cl

clock=pygame.time.Clock()

while (frame<1000) :
world.Step(clock.tick(50)*0.001, 8, 3)
frame+=1
pose=ball.position
pool.update_sound_2d(slot, pose.x, pose.y)
if(frame==500) :
#help(ball.ApplyLinearImpulse)
ball.ApplyLinearImpulse(b2Vec2(-30, 50), ball.position, True) # I have no idea what the last value does.
print "SERVE!\n"
pool.play_stationary("ball.wav", False)
# Force.
If you run the above, you should notice... ur, nothing, since I didn't include the sound files. But let's assume you have the two files it needs, then run it.You should hear a looping sound get louder, until it bounces a bit--at which point the bounce sound should play.Then it stops for a couple seconds, then there is another bounce, and it goes flying into oblivion.It really shouldn't go flying into oblivion. I goofed up somewhere.The solution to the oblivion problem is to use Edges. I seem to remember some confusion as to how to use those with my copy of PyBox2D, so I went with the Rectangle, for the basic test.I could explain that code monstrosity, but I should have started packing by now. So... HTH?

URL: http://forum.audiogames.net/viewtopic.php?pid=233586#p233586




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector

Python crash course

2015-10-02 Thread AudioGames . net Forum — Developers room : CAE_Jones via Audiogames-reflector


  


Python crash course

(Disclaimer: I have never written a tutorial worth anything. This does not try to explain programming concepts, and instead focuses on input/output. First post is basics. Will try to continue into external modules, since those are where all the power lies.)So they say that Python is awesome.But let's just give the tour, and you can decide.This will be fairly thorough, but you absolutely should not try to absorb everything at once. Install Python, get the basics of the command line, and meet me at the next heading, if you don't feel like it's time for all those packages and complex command line features.Here are some important links:Python official site: http://python.orgInstaller for Python 2.7: https://www.python.org/downloads/release/python-2710/Googling "Python Tutorial" might also come in handy.Lots of Python libraries, particularly accessibility-related: http://hg.q-continuum.net/- Specifically, accessible_output2 is the most straightforward way to use text-to-speech and braille output: http://hg.q-continuum.net/accessible_ou … ve/tip.zipYou might also want Pygame: http://pygame.org/Or Pyglet: http://pyglet.orgAnd if you do anything complex enough, you'll want to find Numpy or Scipy, both of which are great if you wan to do low-level audio manipulation.(People who have spent more time with Python will tell you that Pip is an excellent way to easy-install packages. I haven't bothered, so can't comment.)Anyway, let's get on to the instructions.It is advisable to be comfortable using the Command Prompt. You can get away with a few basics easily enough:- you can find the command prompt in Windows, either by using the built-in search feature, or by typing "cmd" or "command" into the run dialog (windows+r). It's probably in c:\windows\system32\cmd.exe.- The most common commands:cd documents^ changes directory to documents, if possible.cd ..^ Moves to the parent directory. SO if you're in c:\my documents, and type cd .., you will move to c:\.c:, d:, e:, f:, etc^ change drive. You need to do this explicitly instead of trying to use cd /d.cd /d c:\users\^ change directory, given the absolute path.pushd c:\users\^ Pushes the current directory onto the stack, then changes to c:\users\. This is useful if you'll want to go back to the previous directory later.popd^ Returns to the last directory on the stack.That's pretty much it. You can use tab and shift+tab to cycle through files and folders, including searching or autocompleting based on what you've already entered.And any file or directory name with spaces or special characters should be surrounded in quotes. So if you want to move to c:\my documents, you'd type:cd /d "c:\my documents"Entering a filename and pressing enter will have windows try to open said file.Some programs take extra command line arguments. This is relevant here, because a lot of packages use a setup.py script, and you need to cd into the corresponding directory and type:setup.py installAnd it will either install the package, or tell you what other packages you need to hunt down. Luckily, just about everything you'd need will be either at one of the above links, or at http://pypi.python.org/If you want to mess with environment variables, you can set it so that you can run the python console by just typing "python" at the command line. But I'm too lazy for that, since I just installed python in c:\python27.Getting startedI'm assuming you have the python console up and running. If not, try typing this at the command line:c:\python27\python.exeThe important part is running python.exe, from wherever it installed.If it works, it should display a message with version number and OS information, then leave you at a prompt that looks like this:>>>I have no idea how to save console sessions. It's probably something straightforward once you figure out what the session is called internally. But, basically, I treat the console as a place to test and debug things.Anyway, basics of syntax:C:\Users\CAE>c:\Python27\python.exe
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello, jys"
Hello, jys
>>> my_number=5
>>> my_number
5
>>> print my_number
5
>>> print "My number is " + my_number + "."
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "With the str function, we see that my number is " + str(my_number) +
"!"
With the str function, we see that my number is 5!
>>> a=my_number+1
>>> a
6
>>> b=a/2
>>> b
3
>>> c=b/2
>>> c
1
>>> c=b/2.0 # explicitly use floating point division.
>>> c
1.5
>>> a%my

Re: Python crash course

2015-10-02 Thread AudioGames . net Forum — Developers room : Ethin via Audiogames-reflector


  


Re: Python crash course

I do recommend python 3.x, however that's just my viewpoint. Most code is easily portable to python3 using lib2to3 but some of it does not port properly and requires editing to work properly. The tutorial I'm about to give, which expands on cae_jones's tutorial, is for Python 3 programmers, although some of it will work on python 2 as well.Functions, conditionals, and loopsIf you did not understand the code writtein in post 3, I will try and explain, in some detail, most of the elements used in that post to clerify exactly what is done. I will, however, not relate to such elements.FunctionsA function is a way of categorizing a lot of code into a simple one liner. For instance, a call to a function called play_3d_sound does a lot of things using that one function call. The function is defined using the def keyword. The code is indented; tabs or spaces are accepted, but a mix of both will result in a syntax error.The s
 yntax for defining a function is as follows:def  (): # codeordef  (, , ...): # codeIf you look at each portion of the function definition syntax, you will notice that the items after the colon (":") are indented by one space. This is called the "indent level" and must always remain the same through the code while writing the function. The only time this should ever differ is if your inside a loop, conditional, class, try-accept block, or with block, or if you have finished the function. We will cover with blocks and try-accept blocks later.An example function would be as follows:def hello (name): print ("Hello,", str(name))Let's brea
 k this function down into segments:def hello (name):This creates the function. A function cannot be called unless it has been defined beforehand.print ("hello", str(name))This is the code of the function. Think of a function as a document on your computer. Inside the function is code that the function utilizes, so think of that code as text you write. The function is your document, which was blank upon definition of the function, but when you add code, your writing paragraphs for, say, a book or thesis paper.Did you notice the str() call inside of the print() statement? It is possible to call functions inside of other functions, just like you can open more doors inside of a building.Keep in mind that if you write this function and never call it, it will sit in memory, never being used. So, let's rewrite the funct
 ion, this time calling it:def hello (name): print ("Hello,", str(name))hello("Ethin")Output:>>> hello("Ethin")Hello, Ethin!>>>Did you notice the blank line after the function definition? This is the terminator of the function. This is not required; Pythonists just use it as an indicator to them that says "Hey, this function ends here." This is also used for terminating loops, classes, exception catchers, etc. You will see it quite often.ConditionalsIf you paid attention in geometry class, you will no that a conditional says "if so and so, then so and so." Of course, you will know that a conditional can be conversed and inversed: "if A, then B.", "if B, then A.", and "If not A, then B." or "If
  A is not B, then C."Python has its own way of doing this:if A: # codeif not A: # codeOf course, there are if... else... elif... conditionals, which go like this:if A: # codeelif B: # codeelse: #codeAn example conditional would be as follows:i = 15if i * i = 225: print ("i is 225!")elif i * i * i = 3375: print ("i is 3375!")else: print ("i is not 225 or 3375!")As you noticed, we defined a variable. A variable must be defined before we could use it.LoopsA loop is a block which basically says, "If A is B, then do B until C."There is also a loop which says, 
 "While A is B, then C" and "while A is in B, then C."These loops are called the for and while loops. The for syntax is as follows:for a in b: # codeReplace 'a' with a variable, and replace 'b' with a list, dictionary, or function call. For instance, here's the most common for loop I use:for i in range (1, 101): print (i)orfor i in xrange (1, 101, 5): print (i)A while loop looks similar:i = 0while i < 100: print (i) i = i + 1This does the following:Declare the variable i with the value 0.Enter the while loop, which conditionally says, "while i is less 
 than 100: "Print i's value.Increase i by 1, while keeping the current value.If we had simply done:i = iWe would have caused an infinite loop, which would have run, indefinitely until control+c (CIGINT (signal interrupt)) was pressed.Well, folks, that's all for now. See you later.

URL: http://forum.audiogames.net/viewtopic.php?pid=233605#p233605




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector

Re: Python crash course

2015-10-02 Thread AudioGames . net Forum — Developers room : dhruv via Audiogames-reflector


  


Re: Python crash course

I have no clue if this will help anyone. But here goes, anyway: classes Think of classes as factories. They produce class instances, which are just class objects but just configured differently. Classes hold functions and variables (which are methods and...something? properties? I have no clue, I just use the damn thing.). Classes are made like this:#a class example
class foo(object):
def __init__(self, num):
self.num = num
def print_num(self):
print self.num
d = foo(5)
d.print_num() inheritance You might have noticed the (object) tag at the end of our class declaration. That means that class foo inherits from the object class. Inheritance, for those of you who are new at programming, is a way to give classes the attributes of their superclasses. Essentially what this means is that I can call any method that exists on object from class foo. You generally inherit from object in python 2 because of old python language stuff (if you wanna know more, just google why use object class python2). Python3 has new style classes (classes which inherit automatically from object) so you don't have to worry about this in python3. list comprehensions (intermediate) List comprehensions are a way to concisely express a concept. I'm not correctly explaining this. Let me go pull a description from google, brb...Okay. So wikipedia tells me that a list comprehension is a syntactic co
 nstruct available in some programming languages for creating a list from existing lists. Basically, you do modifications on lists to produce a new list. Example:l = [i for i in [1, 2, 3, 4, 5]]
print lThis does nothing fancy, just iterates (more on that in a little bit) through the list [1, 2, 3, 4, 5] and produces a list. Now, to do something a little more fancy...from math import sqrt
l = [i**2 for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
print lThis provides us with a list that has i squared. Basically, the list that has numbered is being looped on with the for loop, i is assigned to the current item the loop is working on. i**2 (** is exponentiation) is called, and afterwards i is appended to the list that this list comprehension will produce. The syntax of a list comprehension is as follows: [variable for variable in list if conditional] generator expressions (intermediate) Generator expressions are in some way pretty much same as a list, but they work differently. In a list coprehension, every value gets generated at the time that you type the code for the list comprehension. This easily becomes painful when you're working with huge data. That's where generators become handy. Generators are "lazy", which essentially means that the
 y will only produce the next value when your program asks it to produce it. They aren't generally used, but they become helpful in the specific case when you're working with large data.

URL: http://forum.audiogames.net/viewtopic.php?pid=233613#p233613




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector

Re: Python crash course

2015-10-02 Thread AudioGames . net Forum — Developers room : dhruv via Audiogames-reflector


  


Re: Python crash course

I have no clue if this will help anyone. But here goes, anyway: classes Think of classes as factories. They produce class instances, which are just class objects but just configured differently. Classes hold functions and variables (which are methods and...something? properties? I have no clue, I just use the damn thing.). Classes are made like this:#a class example
class foo(object):
def __init__(self, num):
self.num = num
def print_num(self):
print self.num
d = foo(5)
d.print_num() inheritance You might have noticed the (object) tag at the end of our class declaration. That means that class foo inherits from the object class. Inheritance, for those of you who are new at programming, is a way to give classes the attributes of their superclasses. Essentially what this means is that I can call any method that exists on object from class foo. You generally inherit from object in python 2 because of old python language stuff (if you wanna know more, just google why use object class python2). Python3 has new style classes (classes which inherit automatically from object) so you don't have to worry about this in python3. list comprehensions (intermediate) List comprehensions are a way to concisely express a concept. I'm not correctly explaining this. Let me go pull a description from google, brb...Okay. So wikipedia tells me that a list comprehension is a syntactic co
 nstruct available in some programming languages for creating a list from existing lists. Basically, you do modifications on lists to produce a new list. Example:l = [i for i in [1, 2, 3, 4, 5]]
print lThis does nothing fancy, just iterates (more on that in a little bit) through the list [1, 2, 3, 4, 5] and produces a list. Now, to do something a little more fancy...l = [i**2 for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
print lThis provides us with a list that has i squared. Basically, the list that has numbered is being looped on with the for loop, i is assigned to the current item the loop is working on. i**2 (** is exponentiation) is called, and afterwards i is appended to the list that this list comprehension will produce. The syntax of a list comprehension is as follows: [variable for variable in list if conditional] generator expressions (intermediate) Generator expressions are in some way pretty much same as a list, but they work differently. In a list coprehension, every value gets generated at the time that you type the code for the list comprehension. This easily becomes painful when you're working with huge data. That's where generators become handy. Generators are "lazy", which essentially means that the
 y will only produce the next value when your program asks it to produce it. They aren't generally used, but they become helpful in the specific case when you're working with large data.

URL: http://forum.audiogames.net/viewtopic.php?pid=233613#p233613




___
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector