Presentation is loading. Please wait.

Presentation is loading. Please wait.

PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables.

Similar presentations


Presentation on theme: "PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables."— 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 def printMe(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.


Download ppt "PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables."

Similar presentations


Ads by Google