Commit c94154978b15137dce4f792bfc43b61221e880e9

Luokan luonti selitetty esimerkillä. Teksti puuttuu...
Person.py
(29 / 0)
  
1class Person:
2 def __init__(self, name, sex, mother, father):
3 self._name = name
4 self._mother = mother
5 self._father = father
6 self._spouse = None
7 self._children = set()
8 def name(self):
9 return self._name
10 def marry(self, spouse):
11 self._spouse = spouse
12 def divorce(self, spouse):
13 if not self._spouse: return
14 if spouse is not self._spouse:
15 raise NotMarriedTo(self, spouse)
16 ex = self._spouse
17 self._spouse = None
18 ex.divorce(self)
19 def addChild(self, child):
20 self._children.add(child)
21 def removeChild(self, child):
22 self._children.remove(child)
23 def __str__(self):
24 if self._spouce:
25 s = self._spouce
26 else:
27 s = "-"
28 c = self.string_list_of_children()
29 return "Name: %s\nMother: %s\nFather: %s\nSpouce: %s\nChildren: %s\n" % (self.name(), self._mother.name(), self._father._name(), s, c)
luento.org
(46 / 2)
  
441441
442442
443443
444** Luokan määrittely ja dokumentointi
444** Luokan määrittely ja dokumentointi, olion luonti
445445
446** Olion luonti
446
447#+begin_src python -n :results output :exports both
448 class Person:
449 def __init__(self, name, phone):
450 self._name = name
451 self._phone = phone
452
453 def name(self):
454 return self._name
455 def set_name(self, name):
456 self._name = name
457 return self._name
458
459 def phone(self, phone=None):
460 if phone:
461 self._phone = phone
462 return self._phone
463
464 def __str__(self):
465 return 'Person name: %s phone: %s' % (self.name(), self.phone())
466
467 class NewStylePerson(object):
468 def __init__(self, name):
469 self._name = name
470
471 def get_name(self):
472 return self._name
473 def set_name(self, name):
474 self._name = name
475 return self._name
476 name = property(get_name, set_name)
477
478 # Property phone done likewise, left out for clarity.
479
480 def __str__(self):
481 return 'Person name: %s' % self.name
482
483
484 donald = Person('Donald','555-313')
485 daisy = NewStylePerson('Daisy')
486 print donald
487 print daisy
488#+end_src
489
490
447491
448492** Poikkeuksellisesti: try ... except
449493