Let's start with class. Class is an object that can be created by ourselves. So far I've learned superclass and subclass, which are like parents and children. The children can inherit, extend or override the parents' methods. It is really convenient to have several subclasses to implement the super one. In this way, the whole program is clear and flexible, we can edit the subclass without changing the superclass and work on more details specific for each subclass. A subclass can literally inherit everything that is in the superclass. Whenever a change is needed, it can just modify the relating method by either extending or overriding. Overriding is just write the method again ignoring the superclass while extending is to cite something from the superclass and extend more codes for that. And don't forget to raise an NotImplementedError when the superclass is not able to define a method without a subclass. Just to take up the space for the subclasses to override.
So what is a method? According to my understanding, a method is a piece of code associated with the class, while a function is independent of the class. The basic methods I have learned include __init__, __str__, __repr__, __eq__, __contains__...
For __init__, we have to be careful what variables should we put in the bracket: if the object comes with the parameters, then those parameters should be included as variables in the __init__bracket.
For the parameters we assign to a class, then we can simply include such parameters along the way.
I know my explanation is awful, let's use an example:
def __init__(self, player):
''' (GameState, str) -> NoneType
Initialize new game state self to have state which player plays next
and a list for legal moves.
>>> g = GameState('computer')
>>> g.state
'computer'
>>> g.legal_moves
[]
'''
self.state = player
self.legal_moves = []
This is from assignment 1. Here the list of legal moves is something the object is not born with, it's gained along the way, so we just include it rather than putting it in the bracket.
Then, to distinguish __str__ and __repr__, below is a useful example:
import datetime
today = datetime.datetime.now()
>>>str(today)
'2015-02-11 09:56:20'
>>>repr(today):
'datetime.datetime(2015, 2, 11, 9, 56, 20)'
In short, __repr__ is to make be unambiguous and __str__ is to be readable.
And also, for __eq__, it's not just all parameters should be equal to each other, we should also include the comparison of the class of two objects, using isinstance:
return is instance(self, other) and self.a == other.a...
This need to be remembered, since I have made a mistake on this.
And with __contains__(do not forget the 's' at the end), we can simply use 'a in b' rather than 'b.__contains__(a) ' after defined.
It's important to implement the classes we created with the methods above, they can make your future steps a lot easier.
Above is all I can think of object-oriented programming concepts.
Tschüss!
Dark Fox
No comments:
Post a Comment