Python-Ref > Object oriented programming > Basics > What are objects
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

What are objects

Many high-level programming efforts involve manipulation of data that are beyond simple types like numbers or strings. Such data usually represent real world objects, such as goods, people, web-pages, files, molecules, etc. While such complex data types and their manipulation may be modeled using standard procedural equipment, such as dictionaries, functions, etc., it is not very convenient and often does not correspond to the natural way such data are viewed.
For instance it is much more natural to view a model of persons as one object having different properties, such as name, height, weight, rather that as a set of values in a dictionary. Also the manipulation of such data is much more conveniently done using the object itself, not a bunch of functions working on a set of data.
The following example shows a model of a person based on standard procedural style of coding...
Expand/Shrink
Zdroj: (oop1-1.py)
  1   def introduce_person( person):
  2     print "Hello, my name is %s %s." % (person["given_name"], person["surname"])
  3   
  4   def get_persons_age( person):
  5     import datetime
  6     return datetime.datetime.now().year - person["birth_year"]
  7   
  8   def load_person_info_from_file( filename):
  9     """reads data from a file and returns a persons record,
 10     it is just a fake in this sample code"""
 11     return {"given_name": "Dirk",
 12             "surname": "Gently",
 13             "birth_year": 1957,
 14             "salary": 30000}
 15   
 16   def store_person_info_in_file( person, filename):
 17     """stores persons record in a file,
 18     it is just a fake in this sample code"""
 19     pass
 20   
 21   
 22   person = load_person_info_from_file( "foo.bar")
 23   introduce_person( person)
 24   print "Age:", get_persons_age( person)
 25   print "Old salary:", person["salary"]
 26   person["salary"] /= 2  # must have done something very bad
 27   print "New salary:", person["salary"]
 28   store_person_info_in_file( person, "foo.bar")
stdout:
Hello, my name is Dirk Gently.
Age: 51
Old salary: 30000
New salary: 15000
Doba běhu: 21.8 ms
... and the code below shows the OOP approach (even though it is in some ways non-ideal and naive).
Expand/Shrink
Zdroj: (oop1-2.py)
  1   class Person:
  2   
  3     def __init__( self, surname="", given_name="", birth_year=0, salary=0):
  4       self.surname = surname
  5       self.given_name = given_name
  6       self.birth_year = birth_year
  7       self.salary = salary
  8   
  9     def introduce( self):
 10       print "Hello, my name is %s %s." % (self.given_name, self.surname)
 11   
 12     def get_age( self):
 13       import datetime
 14       return datetime.datetime.now().year - self.birth_year
 15   
 16     def load_from_file( self, filename):
 17       """reads data from a file and returns a persons record,
 18       it is just a fake in this sample code"""
 19       self.given_name = "Dirk"
 20       self.surname = "Gently"
 21       self.birth_year = 1957
 22       self.salary = 30000
 23   
 24     def store_in_file( self, filename):
 25       """stores persons record in a file,
 26       it is just a fake in this sample code"""
 27       pass
 28   
 29   
 30   person = Person()
 31   person.load_from_file( "foo.bar")
 32   person.introduce()
 33   print "Age:", person.get_age()
 34   print "Old salary:", person.salary
 35   person.salary /= 2  # must have done something very bad
 36   print "New salary:", person.salary
 37   person.store_in_file( "foo.bar")
stdout:
Hello, my name is Dirk Gently.
Age: 51
Old salary: 30000
New salary: 15000
Doba běhu: 21.8 ms
The difference between the two codes is not that dramatical, but has basic semantical differences.
Example 1 (procedural) Example 2 (OOP)
Data representation A dictionary:
  • no guarantee of a value being present
  • anybody can modify the data at will
  • need to quote string key names
An object:
  • explicit constructor makes sure all attributes have value
  • access to data may be limited
  • much nicer dot (.) notation
Data manipulation Individual functions:
  • functions have no implicit binding to an object
  • completely different "object" may be submitted
  • possible namespace cluttering
  • name usually contains object type - longer names
Methods (internal functions):
  • methods are bound to the object
  • methods work only on their "own" object
  • method names do not appear in the global namespace
  • different object may use the same method name
The following code snippets show some examples of what can go wrong in the procedural world and cannot (should not) happen in OOP.
Expand/Shrink
Zdroj: (oop1-3.py)
  1   def introduce_person( person):
  2     print "Hello, my name is %s %s." % (person["given_name"], person["surname"])
  3   
  4   def get_persons_age( person):
  5     import datetime
  6     return datetime.datetime.now().year - person["birth_year"]
  7   
  8   # completely different kind of data
  9   person = {"cats": 3, "dogs": 0, "parrots": 2}
 10   introduce_person( person)
stderr:
Traceback (most recent call last):
  File "oop1-3.py", line 10, in ?
    introduce_person( person)
  File "oop1-3.py", line 2, in introduce_person
    print "Hello, my name is %s %s." % (person["given_name"], person["surname"])
KeyError: 'given_name'
Doba běhu: 20.7 ms
Expand/Shrink
Zdroj: (oop1-4.py)
  1   def introduce_person( person):
  2     print "Hello, my name is %s %s." % (person["given_name"], person["surname"])
  3   
  4   def get_persons_age( person):
  5     import datetime
  6     return datetime.datetime.now().year - person["birth_year"]
  7   
  8   def load_person_info_from_file( filename):
  9     """reads data from a file and returns a persons record,
 10     it is just a fake in this sample code"""
 11     return {"given_name": "Dirk",
 12             "surname": "Gently",
 13             "salary": 30000}
 14   
 15   # the data is almost right, but something is missing
 16   person = load_person_info_from_file( "foo.bar")
 17   introduce_person( person)
 18   print "Age:", get_persons_age( person)
stdout:
Hello, my name is Dirk Gently.
Age:
stderr:
Traceback (most recent call last):
  File "oop1-4.py", line 18, in ?
    print "Age:", get_persons_age( person)
  File "oop1-4.py", line 6, in get_persons_age
    return datetime.datetime.now().year - person["birth_year"]
KeyError: 'birth_year'
Doba běhu: 21.4 ms