1 / 9

Python OBJECTS & Classes

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?

braith
Download Presentation

Python OBJECTS & Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python OBJECTS & Classes

  2. 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

  3. Car Object • What are the attributes of a car? • What are the methods of a car?

  4. 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”

  5. 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

  6. 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

  7. 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()

  8. Contact Class Test Code from contact import * #loads contact.py c = Contact() c.name = "Mr. Bui" c.phone = "703.867.5309" c.test()

  9. 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.

More Related