120 likes | 465 Views
Python OBJECTS & Classes. What is an object?. The abstract idea of anything What is in an object: Attributes Characteristics R epresented by internal variables Methods Actions ~ things it can do Represented by internal functions. Car Object. What are the attributes of a car?
E N D
What is an object? • The abstract idea of anything • What is in an object: • Attributes • Characteristics • Represented by internal variables • Methods • Actions ~ things it can do • Represented by internal functions
Car Object • What are the attributes of a car? • What are the methods of a car?
What is a class definition? • class ~ the blueprint/definition of an object • User/programmer-defined datatype Class Template: class CLASSNAME: #attributes var = 12 #methods def f(self): return “Hello”
Point Class Example class Point: x = 0 y = 0 defprintMe(self): print(self.x, self.y) #self is a keyboard that means “itself” #so it’s own variables can be specified
Creating objects from classes • Create an object using this template: varName = ClassName() • Access the internal attributes and methods of an object using the dot . p = Point() #creates an instance of Point p.x = 1 #changes the internal variable x p.y = 3 #changes the internal variable y p.printMe() #calls p’s printMe() method
Contact Class Example class Contact: #the __init__ method runs automatically #when an object is created def __init__(self): self.name = "" self.phone = "" def print(self): print(self.name, "-", self.phone) def test(self): self.print()
Contact Class Test Code from contact import * #loads contact.py c = Contact() c.name = "Mr. Bui" c.phone = "703.867.5309" c.test()
Why do we use objects/classes? • Encapsulate related variables and functions together • Create more organized code • Create classes for future use in other programs • Modular design • Have different people work on different classes at the same time • Etc.