Object Oriented Programming In Python
Understanding Object Oriented Programming, or OOP So far, you have written Python programs in a “Top Down” fashion using functions Now we will learn a new way building and thinking about building software OOP lets you represent real-life objects as software objects You will combine characteristics (called attributes) and behaviors (called methods)
Alien Spacecraft Example If you were to build an alien spacecraft, what would be it’s attributes and behaviors?
Alien Spacecraft Example Attributes: Location, fuel level, engine temperature, current velocity, current direction Behaviors: Move forward, move backward, move up, move down, fire weapons, teleport
Objects and Classes Objects are created (or instantiated in OOP- Speak) from a definition called a class Classes are like blueprints. A class isn’t an object; it is a design for one A builder can create many houses from one set of blueprints A programmer can create many objects from one class
More on Objects and Classes Separate objects can have separate attribute values Just as two houses built from the same blueprint can be decorated differently, two objects of the same class can have their own attribute values
Bank Account Example A bank has one checking account class Attributes: Name, account number, date created, balance Methods: Make deposit, make withdrawl Two objects can be instantiated for two different customers. Each may have their own account number and balance
Simple Python Example class Critter(object) : def talk(self): print("Hi! I am a Critter") def main(): crit = Critter() crit.talk() main() Output: Hi! I am a Critter
Creating A Constructor A constructor is automatically called when the object is instantiated class Critter(object) : def __init__(self): print("A new critter has been born!") def talk(self): print("Hi! I am a Critter") def main(): crit = Critter() crit.talk() main()
Creating Multiple Objects class Critter(object) : def __init__(self): print("A new critter has been born!") def talk(self): print("Hi! I am a Critter") def main(): crit1 = Critter() crit1.talk() crit2 = Critter() crit2.talk() main()
Using Attributes You can have attributes created and initialized when an object is instantiated class Critter(object) : def __init__(self, name): print("A new critter has been born!") self.name = name def talk(self): print("Hi! I am a ", self.name, " Critter") def main(): crit1 = Critter("Dog") crit1.talk() crit2 = Critter("Cat") crit2.talk() main()
Why is OOP important? Makes complex code easier to develop, more reliable, more maintainable and generally better Encapsulation – Lets you change the implementation of an object without affecting other code
Why is oop important? Polymorphism - Lets you have different functions, all with the same name, all doing the same job, but on different data Inheritance – You can write a set of functions and then expand them in different directions without changing or copying them