Movatterモバイル変換


[0]ホーム

URL:


Damian T. Gordon, profile picture
Uploaded byDamian T. Gordon
PPTX, PDF1,923 views

Creating Objects in Python

This document outlines the creation and manipulation of a 'point' class in Python, demonstrating how to define classes, create objects, and add attributes and methods. It explains object initialization, the use of the __init__ method, and how to document class methods using docstrings. Sample code snippets illustrate various class functionalities, such as moving points and calculating the distance between them.

Embed presentation

Downloaded 85 times
Objects in PythonDamian Gordon
Declaring a Class
The Point Classclass MyFirstClass:pass# END Class
The Point Classclass MyFirstClass:pass# END Class“move along, nothingto see here”
The Point Classclass MyFirstClass:pass# END Classclass <ClassName>:<Do stuff># END Class
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
>>> a = MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
The Point Classclass Point:pass# END Classp1 = Point()p2 = Point()
The Point Classclass Point:pass# END Classp1 = Point()p2 = Point()Creating a class
The Point Classclass Point:pass# END Classp1 = Point()p2 = Point()Creating a classCreating objectsof that class
Adding Attributes
The Point Classp1.x = 5p1.y = 4p2.x = 3p2.y = 6print("P1-x, P1-y is: ", p1.x, p1.y);print("P2-x, P2-y is: ", p2.x, p2.y);
The Point Classp1.x = 5p1.y = 4p2.x = 3p2.y = 6print("P1-x, P1-y is: ", p1.x, p1.y);print("P2-x, P2-y is: ", p2.x, p2.y);Adding Attributes:This is all you need todo, just declare them
Python: Object Attributes• In Python the general form of declaring an attribute is asfollows (we call this dot notation):OBJECT. ATTRIBUTE = VALUE
Adding Methods
The Point Classclass Point:def reset(self):self.x = 0self.y = 0# END Reset# END Class
The Point Classclass Point:def reset(self):self.x = 0self.y = 0# END Reset# END ClassAdding Methods:This is all you need
The Point Classp = Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);
The Point Classp = Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);5 4
The Point Classp = Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);5 40 0
Let’s try that again…
The Point Classp = Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);
The Point Classp = Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);
The Point Classp = Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);We can also say:Point.reset(p)
Multiple Arguments
The Point Classclass Point:def reset(self):self.x = 0self.y = 0# END Reset# END Class
The Point Class• We can do this in a slightly different way, as follows:
The Point Classclass Point:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END Class
The Point Classclass Point:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassDeclare a new methodcalled “move” that writesvalues into the object.
The Point Classclass Point:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassDeclare a new methodcalled “move” that writesvalues into the object.Move the values 0 and 0into the class to reset.
Distance between two points
The Point Class• The distance between two points is:dd = √(x2 – x1)2 + (y2 – y1) 2d = √(6 – 2)2 + (5 – 2) 2d = √(4)2 + (3)2d = √16 + 9d = √25d = 5
The Point Class• Let’s see what we have already:
The Point Classclass Point:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END Class
The Point Class• Now let’s add a new method in:
The Point Classimport mathclass Point:def calc_distance(self, other_point):return math.sqrt((self.x – other_point.x)**2 +(self.y – other_point.y)**2)# END calc_distance# END Class d = √(x2 – x1)2 + (y2 – y1)2
The Point Class• Now let’s add some code to make it run:
The Point Classp1 = Point()p2 = Point()p1.move(2,2)p2.move(6,5)print("P1-x, P1-y is: ", p1.x, p1.y)print("P2-x, P2-y is: ", p2.x, p2.y)print("Distance from P1 to P2 is:", p1.calc_distance(p2))p1p2
Initialising an Object
Initialising an Object• What if we did the following:
Initialising an Objectp1 = Point()p1.x = 5print("P1-x, P1-y is: ", p1.x, p1.y);
Initialising an Objectp1 = Point()p1.x = 5print("P1-x, P1-y is: ", p1.x, p1.y);
>>>Traceback (most recent call last):File "C:/Users/damian.gordon/AppData/Local/Programs/Python/Python35-32/Point-error.py",line 11, in <module>print("P1-x, P1-y is: ", p1.x, p1.y);AttributeError: 'Point' object has no attribute 'y‘>>>
Initialising an Object• So what can we do?
Initialising an Object• So what can we do?• We need to create a method that forces the programmers toinitialize the attributes of the class to some starting value, justso that we don’t have this problem.
Initialising an Object• So what can we do?• We need to create a method that forces the programmers toinitialize the attributes of the class to some starting value, justso that we don’t have this problem.• This is called an initialization method.
Initialising an Object• Python has a special name it uses for initialization methods._ _ init _ _()
class Point:def __init__(self,x,y):self.move(x,y)# END Initdef move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassInitialising an Object
Initialising an Objectclass Point:def __init__(self,x,y):self.move(x,y)# END Initdef move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassWhen you create an object fromthis class, you are going to have todeclare initial values for X and Y.
Initialising an Object• So without the initialization method we could do this:– p1 = Point()– p2 = Point()• but with the initialization method we have to do this:– p1 = Point(6,5)– p2 = Point(2,2)
Initialising an Object• And if we forget to include the values, what happens?
Initialising an Object• And if we forget to include the values, what happens?Traceback (most recent call last):File "C:/Users/damian.gordon/AppData/Local/Programs/Python/Python35-32/Point-init.py", line21, in <module>p = Point()TypeError: __init__() missing 2 requiredpositional arguments: 'x' and 'y'
Initialising an Object• But if we want to be lazy we can do the following:
Initialising an Objectdef __init__(self, x=0, y=0):self.move(x,y)# END Init
Initialising an Objectdef __init__(self, x=0, y=0):self.move(x,y)# END Init
Initialising an Object• And then we can do:– p1 = Point()– p2 = Point(2,2)
Initialising an Object• And then we can do:– p1 = Point()– p2 = Point(2,2)If we don’t supply any values, theinitialization method will set thevalues to 0,0.
Initialising an Object• And then we can do:– p1 = Point()– p2 = Point(2,2)If we don’t supply any values, theinitialization method will set thevalues to 0,0.But we can also supply the values,and the object is created with thesedefault values.
Documenting the Methods
Documenting the Methods• Python is considered one of the most easyprogramming languages, but nonetheless a vital partof object-orientated programming is to explain whateach class and method does to help promote objectreuse.
Documenting the Methods• Python supports this through the use ofdocstrings.• These are strings enclosed in either quotes(‘) ordoublequotes(“) just after the class or methoddeclaration.
Documenting the Methodsclass Point:“Represents a point in 2D space”def __init__(self,x,y):‘Initialise the position of a new point’self.move(x,y)# END Init
Documenting the Methodsdef move(self,a,b):‘Move the point to a new location’self.x = aself.y = b# END Movedef reset(self):‘Reset the point back to the origin’self.move(0,0)# END Reset
Initialising an Object• Now run the program, and then do:>>>>>> help (Point)
Initialising an Object• And you’ll get:Help on class Point in module __main__:class Point(builtins.object)| Represents a point in 2D space|| Methods defined here:|| calc_distance(self, other_point)| Get the distance between two points|| move(self, a, b)| Move the point to a new location|| reset(self)| Reset the point back to the origin| ----------------------------------------------
etc.

Recommended

PDF
Object oriented approach in python programming
PPTX
Constructors and Destructor in C++
PDF
Python libraries
PPTX
Templates in c++
PPTX
Python Programming Essentials - M20 - Classes and Objects
PPT
File handling
PDF
Looking at how Scratch and Python compare
PPT
How to execute a C program
PDF
Python programming : Classes objects
PDF
Python basic
PPTX
Functions in python slide share
PPTX
Python Exception Handling
PPTX
Variables in python
PPTX
Functions in python
PPTX
Object oriented programming in python
PPTX
Python Functions
PPSX
Modules and packages in python
PPT
Java: Java Applets
PDF
Python programming : Strings
PDF
PDF
Generic Programming
PDF
Function in Python
PPTX
Data file handling in python introduction,opening & closing files
PPTX
Files in c++
PDF
Strings in java
PPTX
Getting Started with Python
PPTX
Data Type in C Programming
PPTX
Python Flow Control
PPTX
Python: Modules and Packages
PPTX
Python: Migrating from Procedural to Object-Oriented Programming

More Related Content

PDF
Object oriented approach in python programming
PPTX
Constructors and Destructor in C++
PDF
Python libraries
PPTX
Templates in c++
PPTX
Python Programming Essentials - M20 - Classes and Objects
PPT
File handling
PDF
Looking at how Scratch and Python compare
PPT
How to execute a C program
Object oriented approach in python programming
Constructors and Destructor in C++
Python libraries
Templates in c++
Python Programming Essentials - M20 - Classes and Objects
File handling
Looking at how Scratch and Python compare
How to execute a C program

What's hot

PDF
Python programming : Classes objects
PDF
Python basic
PPTX
Functions in python slide share
PPTX
Python Exception Handling
PPTX
Variables in python
PPTX
Functions in python
PPTX
Object oriented programming in python
PPTX
Python Functions
PPSX
Modules and packages in python
PPT
Java: Java Applets
PDF
Python programming : Strings
PDF
PDF
Generic Programming
PDF
Function in Python
PPTX
Data file handling in python introduction,opening & closing files
PPTX
Files in c++
PDF
Strings in java
PPTX
Getting Started with Python
PPTX
Data Type in C Programming
PPTX
Python Flow Control
Python programming : Classes objects
Python basic
Functions in python slide share
Python Exception Handling
Variables in python
Functions in python
Object oriented programming in python
Python Functions
Modules and packages in python
Java: Java Applets
Python programming : Strings
Generic Programming
Function in Python
Data file handling in python introduction,opening & closing files
Files in c++
Strings in java
Getting Started with Python
Data Type in C Programming
Python Flow Control

Viewers also liked

PPTX
Python: Modules and Packages
PPTX
Python: Migrating from Procedural to Object-Oriented Programming
PPTX
Python: Third-Party Libraries
PPTX
Python: Basic Inheritance
PPTX
Python: Polymorphism
PPTX
Introduction to Python programming
PPTX
Python: Multiple Inheritance
PPTX
Python: Manager Objects
PPTX
Python: Design Patterns
PPTX
Python: Access Control
PPTX
The Extreme Programming (XP) Model
PPTX
Object-Orientated Design
PPTX
Python: The Iterator Pattern
Python: Modules and Packages
Python: Migrating from Procedural to Object-Oriented Programming
Python: Third-Party Libraries
Python: Basic Inheritance
Python: Polymorphism
Introduction to Python programming
Python: Multiple Inheritance
Python: Manager Objects
Python: Design Patterns
Python: Access Control
The Extreme Programming (XP) Model
Object-Orientated Design
Python: The Iterator Pattern

Similar to Creating Objects in Python

PPTX
Class, object and inheritance in python
PPTX
Python – Object Oriented Programming
PPT
08-classes-objects.ppt
PPTX
VTU Python Module 5 , Class and Objects and Debugging
PPT
OOC in python.ppt
PPT
Python - Classes and Objects, Inheritance
PPTX
Module-5-Classes and Objects for Python Programming.pptx
PPT
Lecture on Python class -lecture123456.ppt
PPT
Lecture topic - Python class lecture.ppt
PDF
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
PDF
Module IV_updated(old).pdf
PPTX
object oriented porgramming using Java programming
PPTX
IPP-M5-C1-Classes _ Objects python -S2.pptx
PPTX
Module 4.pptx
PPT
08-classes-objects.ppt
PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PPTX
Python 2. classes- cruciql for students objects1.pptx
PPTX
Lecture 6 python oop (ewurc)
PDF
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
Class, object and inheritance in python
Python – Object Oriented Programming
08-classes-objects.ppt
VTU Python Module 5 , Class and Objects and Debugging
OOC in python.ppt
Python - Classes and Objects, Inheritance
Module-5-Classes and Objects for Python Programming.pptx
Lecture on Python class -lecture123456.ppt
Lecture topic - Python class lecture.ppt
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
Module IV_updated(old).pdf
object oriented porgramming using Java programming
IPP-M5-C1-Classes _ Objects python -S2.pptx
Module 4.pptx
08-classes-objects.ppt
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Python 2. classes- cruciql for students objects1.pptx
Lecture 6 python oop (ewurc)
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING

More from Damian T. Gordon

PPTX
Introduction to Prompts and Prompt Engineering
PPTX
An Introduction to Generative Artificial Intelligence
PPTX
Introduction to Vibe Coding and Vibe Engineering
PPTX
Hyperparameter Tuning in Neural Networks
PPTX
The Use of Data and Datasets in Data Science
PPTX
Some Common Errors that Generative AI Produces
PPTX
Studying and Notetaking: Some Suggestions
PPTX
Exam Preparation: Some Ideas and Suggestions
PPTX
Writing an Abstract: A Question-based Approach
DOC
A CheckSheet for Inclusive Software Design
PPTX
TRIZ: Theory of Inventive Problem Solving
PPTX
Using GenAI for Universal Design for Learning
PPTX
A History of Versions of the Apple MacOS
PPTX
A History of Different Versions of Microsoft Windows
PPTX
Early 20th Century Modern Art: Movements and Artists
PPTX
Some Ethical Considerations of AI and GenAI
PPTX
The Growth Mindset: Explanations and Activities
PPTX
An Introduction to Green Computing with a fun quiz.
PPTX
Copyright and Creative Commons Considerations
PPTX
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Introduction to Prompts and Prompt Engineering
An Introduction to Generative Artificial Intelligence
Introduction to Vibe Coding and Vibe Engineering
Hyperparameter Tuning in Neural Networks
The Use of Data and Datasets in Data Science
Some Common Errors that Generative AI Produces
Studying and Notetaking: Some Suggestions
Exam Preparation: Some Ideas and Suggestions
Writing an Abstract: A Question-based Approach
A CheckSheet for Inclusive Software Design
TRIZ: Theory of Inventive Problem Solving
Using GenAI for Universal Design for Learning
A History of Versions of the Apple MacOS
A History of Different Versions of Microsoft Windows
Early 20th Century Modern Art: Movements and Artists
Some Ethical Considerations of AI and GenAI
The Growth Mindset: Explanations and Activities
An Introduction to Green Computing with a fun quiz.
Copyright and Creative Commons Considerations
68 Ways that Data Science and AI can help address the UN Sustainability Goals

Recently uploaded

PDF
DEFINITION OF COMMUNITY Sociology. .pdf
PDF
Multimodal and Multimedia AI - by Ms. Oceana Wong
PDF
AI Workflows and Workflow Rhetoric - by Ms. Oceana Wong
PDF
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
PPTX
Photography Pillar 1 The Subject PowerPoint
PDF
45 ĐỀ LUYỆN THI IOE LỚP 8 THEO CHƯƠNG TRÌNH MỚI - NĂM HỌC 2024-2025 (CÓ LINK ...
PPTX
Plant Breeding: Its History and Contribution
PDF
CXC-AD Associate Degree Handbook (Revised)
PPTX
Time Series Analysis - Weighted (Unequal) Moving Average Method
PDF
Digital Electronics – Registers and Their Applications
PDF
Conferencia de Abertura_Virgilio Almeida.pdf
PPTX
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
PPTX
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
PPTX
Time Series Analysis - Meaning, Definition, Components and Application
PPTX
A Presentation of PMES 2025-2028 with Salient features.pptx
PPTX
The hidden treasures Grade 5 Story with Motive Questions.pptx
PPTX
General Wellness & Restorative Tonic: Draksharishta
PPTX
DEPED MEMORANDUM 089, 2025 PMES guidelines pptx
PDF
*Unit-II A (Elements of Communication & Communication Style Matrix)
PPTX
Chapter 3. Pharmaceutical Aids (pharmaceutics)
DEFINITION OF COMMUNITY Sociology. .pdf
Multimodal and Multimedia AI - by Ms. Oceana Wong
AI Workflows and Workflow Rhetoric - by Ms. Oceana Wong
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
Photography Pillar 1 The Subject PowerPoint
45 ĐỀ LUYỆN THI IOE LỚP 8 THEO CHƯƠNG TRÌNH MỚI - NĂM HỌC 2024-2025 (CÓ LINK ...
Plant Breeding: Its History and Contribution
CXC-AD Associate Degree Handbook (Revised)
Time Series Analysis - Weighted (Unequal) Moving Average Method
Digital Electronics – Registers and Their Applications
Conferencia de Abertura_Virgilio Almeida.pdf
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
Time Series Analysis - Meaning, Definition, Components and Application
A Presentation of PMES 2025-2028 with Salient features.pptx
The hidden treasures Grade 5 Story with Motive Questions.pptx
General Wellness & Restorative Tonic: Draksharishta
DEPED MEMORANDUM 089, 2025 PMES guidelines pptx
*Unit-II A (Elements of Communication & Communication Style Matrix)
Chapter 3. Pharmaceutical Aids (pharmaceutics)

Creating Objects in Python

  • 1.
  • 2.
  • 3.
    The Point ClassclassMyFirstClass:pass# END Class
  • 4.
    The Point ClassclassMyFirstClass:pass# END Class“move along, nothingto see here”
  • 5.
    The Point ClassclassMyFirstClass:pass# END Classclass <ClassName>:<Do stuff># END Class
  • 6.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 7.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 8.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 9.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 10.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 11.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 12.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 13.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 14.
    >>> a =MyFirstClass()>>> print(a)<__main__.MyFirstClass object at 0x02D60B10>>>> b = a>>> print(b)<__main__.MyFirstClass object at 0x02D60B10>>>> b = MyFirstClass()>>> print(b)<__main__.MyFirstClass object at 0x02D60B30>
  • 15.
    The Point ClassclassPoint:pass# END Classp1 = Point()p2 = Point()
  • 16.
    The Point ClassclassPoint:pass# END Classp1 = Point()p2 = Point()Creating a class
  • 17.
    The Point ClassclassPoint:pass# END Classp1 = Point()p2 = Point()Creating a classCreating objectsof that class
  • 18.
  • 19.
    The Point Classp1.x= 5p1.y = 4p2.x = 3p2.y = 6print("P1-x, P1-y is: ", p1.x, p1.y);print("P2-x, P2-y is: ", p2.x, p2.y);
  • 20.
    The Point Classp1.x= 5p1.y = 4p2.x = 3p2.y = 6print("P1-x, P1-y is: ", p1.x, p1.y);print("P2-x, P2-y is: ", p2.x, p2.y);Adding Attributes:This is all you need todo, just declare them
  • 21.
    Python: Object Attributes•In Python the general form of declaring an attribute is asfollows (we call this dot notation):OBJECT. ATTRIBUTE = VALUE
  • 22.
  • 23.
    The Point ClassclassPoint:def reset(self):self.x = 0self.y = 0# END Reset# END Class
  • 24.
    The Point ClassclassPoint:def reset(self):self.x = 0self.y = 0# END Reset# END ClassAdding Methods:This is all you need
  • 25.
    The Point Classp= Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);
  • 26.
    The Point Classp= Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);5 4
  • 27.
    The Point Classp= Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);5 40 0
  • 28.
  • 29.
    The Point Classp= Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);
  • 30.
    The Point Classp= Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);
  • 31.
    The Point Classp= Point()p.x = 5p.y = 4print("P-x, P-y is: ", p.x, p.y);p.reset()print("P-x, P-y is: ", p.x, p.y);We can also say:Point.reset(p)
  • 32.
  • 33.
    The Point ClassclassPoint:def reset(self):self.x = 0self.y = 0# END Reset# END Class
  • 34.
    The Point Class•We can do this in a slightly different way, as follows:
  • 35.
    The Point ClassclassPoint:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END Class
  • 36.
    The Point ClassclassPoint:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassDeclare a new methodcalled “move” that writesvalues into the object.
  • 37.
    The Point ClassclassPoint:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassDeclare a new methodcalled “move” that writesvalues into the object.Move the values 0 and 0into the class to reset.
  • 38.
  • 39.
    The Point Class•The distance between two points is:dd = √(x2 – x1)2 + (y2 – y1) 2d = √(6 – 2)2 + (5 – 2) 2d = √(4)2 + (3)2d = √16 + 9d = √25d = 5
  • 40.
    The Point Class•Let’s see what we have already:
  • 41.
    The Point ClassclassPoint:def move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END Class
  • 42.
    The Point Class•Now let’s add a new method in:
  • 43.
    The Point Classimportmathclass Point:def calc_distance(self, other_point):return math.sqrt((self.x – other_point.x)**2 +(self.y – other_point.y)**2)# END calc_distance# END Class d = √(x2 – x1)2 + (y2 – y1)2
  • 44.
    The Point Class•Now let’s add some code to make it run:
  • 45.
    The Point Classp1= Point()p2 = Point()p1.move(2,2)p2.move(6,5)print("P1-x, P1-y is: ", p1.x, p1.y)print("P2-x, P2-y is: ", p2.x, p2.y)print("Distance from P1 to P2 is:", p1.calc_distance(p2))p1p2
  • 46.
  • 47.
    Initialising an Object•What if we did the following:
  • 48.
    Initialising an Objectp1= Point()p1.x = 5print("P1-x, P1-y is: ", p1.x, p1.y);
  • 49.
    Initialising an Objectp1= Point()p1.x = 5print("P1-x, P1-y is: ", p1.x, p1.y);
  • 50.
    >>>Traceback (most recentcall last):File "C:/Users/damian.gordon/AppData/Local/Programs/Python/Python35-32/Point-error.py",line 11, in <module>print("P1-x, P1-y is: ", p1.x, p1.y);AttributeError: 'Point' object has no attribute 'y‘>>>
  • 51.
    Initialising an Object•So what can we do?
  • 52.
    Initialising an Object•So what can we do?• We need to create a method that forces the programmers toinitialize the attributes of the class to some starting value, justso that we don’t have this problem.
  • 53.
    Initialising an Object•So what can we do?• We need to create a method that forces the programmers toinitialize the attributes of the class to some starting value, justso that we don’t have this problem.• This is called an initialization method.
  • 54.
    Initialising an Object•Python has a special name it uses for initialization methods._ _ init _ _()
  • 55.
    class Point:def __init__(self,x,y):self.move(x,y)#END Initdef move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassInitialising an Object
  • 56.
    Initialising an ObjectclassPoint:def __init__(self,x,y):self.move(x,y)# END Initdef move(self,a,b):self.x = aself.y = b# END Movedef reset(self):self.move(0,0)# END Reset# END ClassWhen you create an object fromthis class, you are going to have todeclare initial values for X and Y.
  • 57.
    Initialising an Object•So without the initialization method we could do this:– p1 = Point()– p2 = Point()• but with the initialization method we have to do this:– p1 = Point(6,5)– p2 = Point(2,2)
  • 58.
    Initialising an Object•And if we forget to include the values, what happens?
  • 59.
    Initialising an Object•And if we forget to include the values, what happens?Traceback (most recent call last):File "C:/Users/damian.gordon/AppData/Local/Programs/Python/Python35-32/Point-init.py", line21, in <module>p = Point()TypeError: __init__() missing 2 requiredpositional arguments: 'x' and 'y'
  • 60.
    Initialising an Object•But if we want to be lazy we can do the following:
  • 61.
    Initialising an Objectdef__init__(self, x=0, y=0):self.move(x,y)# END Init
  • 62.
    Initialising an Objectdef__init__(self, x=0, y=0):self.move(x,y)# END Init
  • 63.
    Initialising an Object•And then we can do:– p1 = Point()– p2 = Point(2,2)
  • 64.
    Initialising an Object•And then we can do:– p1 = Point()– p2 = Point(2,2)If we don’t supply any values, theinitialization method will set thevalues to 0,0.
  • 65.
    Initialising an Object•And then we can do:– p1 = Point()– p2 = Point(2,2)If we don’t supply any values, theinitialization method will set thevalues to 0,0.But we can also supply the values,and the object is created with thesedefault values.
  • 66.
  • 67.
    Documenting the Methods•Python is considered one of the most easyprogramming languages, but nonetheless a vital partof object-orientated programming is to explain whateach class and method does to help promote objectreuse.
  • 68.
    Documenting the Methods•Python supports this through the use ofdocstrings.• These are strings enclosed in either quotes(‘) ordoublequotes(“) just after the class or methoddeclaration.
  • 69.
    Documenting the MethodsclassPoint:“Represents a point in 2D space”def __init__(self,x,y):‘Initialise the position of a new point’self.move(x,y)# END Init
  • 70.
    Documenting the Methodsdefmove(self,a,b):‘Move the point to a new location’self.x = aself.y = b# END Movedef reset(self):‘Reset the point back to the origin’self.move(0,0)# END Reset
  • 71.
    Initialising an Object•Now run the program, and then do:>>>>>> help (Point)
  • 72.
    Initialising an Object•And you’ll get:Help on class Point in module __main__:class Point(builtins.object)| Represents a point in 2D space|| Methods defined here:|| calc_distance(self, other_point)| Get the distance between two points|| move(self, a, b)| Move the point to a new location|| reset(self)| Reset the point back to the origin| ----------------------------------------------
  • 73.

[8]ページ先頭

©2009-2025 Movatter.jp