Содержание
- 2. Attribute Inheritance Search The OOP story in Python boils down to this expression: object.attribute It means
- 3. Main concepts behind Python classes Classes and instances are almost identical—each type’s main purpose is to
- 4. Examples
- 5. Class Objects The class statement creates a class object and assigns it a name. Just like
- 6. The simplest: try it >>> list(rec.__dict__.keys()) ['age', '__module__', '__qualname__', '__weakref__', 'name', '__dict__', '__doc__'] >>> list(name for
- 7. Classes Versus Dictionaries: compare
- 8. Classes Versus Dictionaries: compare >>> class Person: def __init__(self, name, jobs, age=None): # class = data
- 9. Try it: class FirstClass: def setdata(self, value): self.data = value def display(self): print(self.data) x = FirstClass()
- 10. Try it: class SecondClass(FirstClass): def display(self): print('Current value = "%s"' % self.data) z = SecondClass() z.setdata(42)
- 11. Calling superclass methods class Super: def __init__(self, x): ...default code... class Sub(Super): def __init__(self, x, y):
- 12. Classes Are Attributes in Modules from modulename import FirstClass # Copy name into my scope class
- 13. General form class name(superclass,...): # Assign to name attr = value # Shared class data def
- 14. Try it: class SharedData: spam = 42 x = SharedData() y = SharedData() x.spam, y.spam #
- 15. Storing the same name in two places class MixedNames: data = 'spam' # class attribute not
- 16. Abstract classes: try it class Super: def method(self): print('in Super.method') def delegate(self): self.action() # Expected to
- 17. Abstract classes 3.X – special syntax from abc import ABCMeta, abstractmethod class Super(metaclass=ABCMeta): @abstractmethod def method(self,
- 18. Operator overloading Methods named with double underscores (__X__) are special hooks (__init__, __add__, __str__, …) Such
- 19. Introspection Tools • The built-in instance.__class__ attribute provides a link from an instance to the class
- 20. Storing Objects: Pickles and Shelves pickle Serializes arbitrary Python objects to and from a string of
- 21. Pickles and Shelves: the whole process Pickle module is super-general object formatting and deformatting tool: it
- 22. Try it: from person import Person, Manager # see Mark Lutz, page 844 bob = Person('Bob
- 23. Try it: >>> import shelve >>> db = shelve.open('persondb') >>> len(db) >>> list(db.keys()) ['Sue Jones', 'Tom
- 24. Real persistence import shelve db = shelve.open('persondb') for key in sorted(db): print(key, '\t=>', db[key]) sue =
- 26. Скачать презентацию