Section 8 Menu
- Introduction
Introduction
https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478286#questions
Object Oriented Programming (OOP) allows programmers to create their own objects that have4 methods and attributes. Recall that after defining a string, list, dictionary or other objects, you are able to call methods off them with the .method_name() syntax.
These methods act as functions that use information about the object, as well as the object itself to return results, or change the current object.
- Examples:
- Appending an item to a list
- counting the occurrences of an element in a tuple.
OOP allows users to create their own objects. In general, OOPs allows us to create code that is repeatable and organized.
For much larger scripts of Python code, functions by themselves aren’t enough for organization and repeatability. Commonly repeated tasks and objects can be defined with OOP to create code that is more usable.
Class
Objects are defined using the ‘class’ keyword. Objects are often called ‘classses’
- Use CamelCase where every word is capitalized.
class NameOfClass():
__init__ method
Allows you to create an instance of the actual object.
- self is a keyword that allows class methods to reference the class’s attributes
- assign the parameters passed in as attributes to the object. This prevents mistaking them from global variables.
def __init__(self, param1, param2, ...):
self.param1 = param1
self.param2 = param2
Object methods
Functions that support the object. Use these methods to interact with the object.
def some_method(self):
#do some stuff
Attributes and Class Keyword
https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478292#questions
Simplest Class
class Sample():
pass
__init__ constructor
- Is called automatically when a new object is created.
- ‘self’ refers it itself. This is usually called ‘behind the scenes’ with other languages, but is displayed in Python.
- self ‘could’ be another variable, but strongly recommended to use ‘self’
class Dog():
def __init___(self, breed):
self.breed = breed
my_dog = Dog()
TypeError: __init__() missing 1 required positional argument: ‘breed’
my_dog = Dog(breed='Lab') type(my_dog)
__main__.Dog
my_dog.breed
‘Lab’
Class Object Attributes and Methods
https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478294#questions
These allow you to define attributes that are standard or shared among all instances of the object vs. attributes that are specific to each object.
Class Object Example
class Dog():
# Class Object Attributes
# These are the same for any instance of the class.
# note that the 'self' keyword is NOT used here.
species = 'mammal'
def __init___(self, breed, name):
self.breed = breed
Methods
Functions associated with an object.
def bark(self, number):
for i in range(0,number):
print("Woof! My name is {}".format(self.name))
print("I am a {}.".format(self.species))
print("I am a {}.".format(Dog.species))
my_dog = Dog('Lab', 'Shotgun')
my_dog.bark(2)
Woof! My name is Shotgun
Woof! My name is Shotgun
I am a mammal.
I am a mammal.
Inheritance and Polymorphism
https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478298#questions
<h2>Inheritance</h2>
Using classes that have already been defined.
class Animal():
def __init__(self):
print("Animal created")
def who_am_i(self):
print("I am an animal.")
def eat(self):
print("I am eating.")
myanimal = Animal() myanimal.who_am_i() myanimal.eat()
Animal created
I am an animal.
I am eating.
Create a new dpg class that inherits Animal and can use it’s methods
class Dog(Animal):
def __init(self):
Animal.__init__(self)
mypet = Dog() mypet.eat()
Polymorphism
Polymorphism refers to the way different object classes can share the same method name.
class Dog():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says 'Woof!'"
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says 'Meow!'"
puppy = Dog('Spot')
kitty = Cat('Fluffy')
print(puppy.speak())
print(kitty.speak())
Spot says ‘Woof!’
Fluffy says ‘Meow!’
for pet in [puppy, kitty]:
print(type(pet))
print(pet.speak())
<class ‘__main__.Dog’>
Spot says ‘Woof!’
<class ‘__main__.Cat’>
Fluffy says ‘Meow!’
def pet_speak(pet)
print(pet.speak())
pet_speak(kitty)
Fluffy says ‘Meow!’
Abstract Classes
Abstract classes are classes that are never expected to instantiated themselves, but are created strictly to serve as a base class for other classes.
class Animal():
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
myanimal = Animal('Fluffy')
myanimal.speak()
NotImplementedError: Subclass must implement this abstract method
class Dog(Animal):
def speak(self):
return self.name + " Says 'Wooooof!!'"
mydog = Dog('Fido')
print(mydog.speak())
Fido Says ‘Wooooof!!’
41% course complete
Special Magic / Dundar Methods
https://www.udemy.com/complete-python-bootcamp/learn/lecture/9478306#questions
__str__, __len__, __del__
class Book():
def __init__(self,title, author, pages):
self.title=title
self.author=author
self.pages=pages
def __str__(self):
return f"{self.title} by {self.author}"
def __len__(self):
return self.pages
def __del__(self):
print(f"Book {self.title} by {self.author} has been deleted.")
b = Book('my book','me',3)
print(b)
print(len(b))
del b
print(b)
mybook by me
3
Book my book by me has been deleted.
NameError: name ‘b’ is not defined