![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#11 |
|
Banned
![]() ![]() |
That's pretty cool. Mind explaining what's happening though when you refer each class and etc? I can't really learn how to make my own in my own situations without seeing the thinking process behind it.
![]() |
|
|
|
|
|
#12 | |
|
Programmer
Join Date: Apr 2005
Posts: 73
Rep Power: 4
![]() |
Quote:
x = str("foo")
print x
print type(x)
print dir(x)If str() were only a function, you could fake a (basic) string class like so: class MyStr(object):
def __init__(self, txt):
self.txt = txt
def __str__(self):
return self.txt
x = MyStr("foo")
print x
print type(x)
print dir(x)You'll notice that in my class definitions, the first parameter of every method is "self" [There are exceptions, but you won't meet those for a long while] "self" refers to the particular instance of that class. It's why paper and paper2 have different states and self.lit only refers to the lit state of that particular piece of paper. __init__() is the function that is automagically called when an object is created. class Test(object):
def __init__(self, txt):
print "calling __init__ of %s with arg '%s'."%(self, txt)
self.txt = txt
i1 = Test("I'm i1")
i2 = Test("I'm i2")
print i1.txt
print i2.txt # <-- Different from i1.txt
i1.txt = "Change in i1"
print i1.txt #<-- Changes
print i2.txt #<-- Doesn't change!Classes are templates for producing building blocks. Some objects will have only a single class based on the object base class. Others will have more of a hierarchy, such as Paper(). So - how do you build a system using classes? Well if you think about an object - say a scroll - it will have certain behaviours associated with it. A scroll can be: * Read * Written on * Put into a container * Picked up * Dropped * Cut * Lit Other things can also be acted on in those ways, but not everything has all those behaviours - for instance a rope bridge might be able to be cut but it certainly can't be picked up or read. So each chunk of behaviours should be a class. Classes can subclass other classes - that is, they inherit default behaviours [eg M_Burnable inherits extinguish() from M_Lightable] and can replace those they need to replace [just as M_Burnable replaces the light() function that it inherits from M_Lightable] Have a play - use lots of print statements; the dir() function may also be handy for showing what methods an object has. Try adding methods, expanding them, creating more classes and beefing up the objects provided. --OH. |
|
|
|
|
|
|
#13 |
|
Banned
![]() ![]() |
Wow. Thanks a lot. That really helped.
class num(object):
def __init__(self, txt):
self.txt = txt
print self.txt
def add(self):
self.txt += 1
print self.txt
num = num(1)
for a in range (9): num.add()Hurray, I did something with classes. Thanks again! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|