seafoid wrote:
Hey Guys,
I have started to read over classes as a brief respite from my parsing
problem.
When a class is defined, how does the class access the data upon which
the
class should act?
Example:
class Seq:
def __init__(self, data, alphabet = Alphabet.generic_alphabet):
self.data = data self.alphabet = alphabet
def
tostring(self):
return self.data
def tomutable(self):
return MutableSeq(self.data, self.alphabet)
def count(self, item):
return len([x for x in self.data if x == item])
I know what it should do, but have no idea how to feed it the data.
Methinks I need to invest in actual computing books as learning from
biologists is hazy!
Kind regards,
Seafoid.
Steve's message was good, but I feel he kind of jumped in the middle. A
class is a description of a type of object, and the behaviors and data
that each instance of the object supports.
You create the object by using the class name like a function call. The
arguments to that "call" are passed to the __init__ method.
So obj = Seq("abcd") or obj = Seq("defg", "abcdefg") would each
create an object of the class. But generally, many objects will exist,
each with different data.
The data in the object is accessed in what appears to be the "self"
namespace. The name self is just a convention, but it's the first
argument of each method of the class. So when somebody calls the
count() method, they pass 'item' a value, but self is used to refer to
that particular object's data.
So how does 'self' get assigned? That's what Steve was describing.
When you use the syntax:
obj.count("value")
you actually call the count method with self referring to "obj" and item
referring to "value". obj does double-duty here, both defining which
class' count() method will be called, and also supplying the first
parameter to the call, the "self" parameter.
There are more complex things that can go on, like creating "bound"
function objects, but I think this should get you pretty far.
One other point: you should always derive a class from some other
class, or 'object' by default. So you should being the class definition
by:
class Seq(object):
Why? It mainly has to do with super(). But in any case if you omit the
'object' it's an "old style" class, and that's not even supported in
3.x, so it's better to just get in the habit before it matters.