Skip to content

Instantly share code, notes, and snippets.

@labeveryday
Last active May 4, 2022 12:52
Show Gist options
  • Save labeveryday/d6ee70ce35a49ee0de0fd44b65ee5543 to your computer and use it in GitHub Desktop.
Save labeveryday/d6ee70ce35a49ee0de0fd44b65ee5543 to your computer and use it in GitHub Desktop.
Example of Object Oriented Programming in Python
# Here is an example of OOP in Python
class Device:
"""First we define a class with attributes.
Self represents the class itself. We can use this to reference attributes
and methods from within the class"""
def __init__(self, name, ip):
self.name = name
self.ip = ip
def print_name(self):
"""Next we create methods that we can use."""
print(f"The device name is {self.name}")
def print_ip(self):
print(f"The device ip is {self.ip}")
def print_everything(self):
print(f"device name: {self.name}\ndevice ip: {self.ip}")
if __name__ == "__main__":
# Here we create a new Device class instance
# We do this by passing in the required args
# Then we assign it to a variable named device
device = Device("cisco", "192.168.1.1")
# Here we print each class attribute
print(device.name)
print(device.ip)
# Here we can see all attributes and methods in our device object
print(dir(device))
# Now call each method in our class
device.print_name()
device.print_ip()
device.print_everything()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment