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

More Related Content

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

What's hot

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

Viewers also liked

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

Similar to Creating Objects in Python

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

More from Damian T. Gordon

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

Recently uploaded

PPTX
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
PPTX
ATTENTION - PART 1.pptx cognitive processes -For B.Sc I Sem By Mrs.Shilpa Hot...
PDF
AI Chatbots and Prompt Engineering - by Ms. Oceana Wong
PPTX
Finals - History and Geography Quiz - Around the World in 80 Questions - IITK
PPTX
Time Series Analysis - Meaning, Definition, Components and Application
PDF
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
PDF
Multimodal and Multimedia AI - by Ms. Oceana Wong
PDF
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
PPTX
Quarter 3 lesson 2 of English Grade 8.pptx
PPTX
Time Series Analysis - Least Square Method Fitting a Linear Trend Equation
PPTX
Screening and Selecting Studies for Systematic Review Dr Reginald Quansah
PPTX
The hidden treasures Grade 5 Story with Motive Questions.pptx
PPTX
Chapter 3. Pharmaceutical Aids (pharmaceutics)
PPTX
DEPED MEMORANDUM 089, 2025 PMES guidelines pptx
PPTX
kklklklklklklklk;lkpoipor[3rjdkjoe99759893058085
PPTX
Plant Breeding: Its History and Contribution
PPTX
LYMPHATIC SYSTEM.pptx it includes lymph, lymph nodes, bone marrow, spleen
PDF
AI and ICT for Teaching and Learning, Induction-cum-Training Programme, 5th 8...
PPTX
A Presentation of PMES 2025-2028 with Salient features.pptx
PPTX
What are New Features in Purchase _Odoo 18
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
ATTENTION - PART 1.pptx cognitive processes -For B.Sc I Sem By Mrs.Shilpa Hot...
AI Chatbots and Prompt Engineering - by Ms. Oceana Wong
Finals - History and Geography Quiz - Around the World in 80 Questions - IITK
Time Series Analysis - Meaning, Definition, Components and Application
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
Multimodal and Multimedia AI - by Ms. Oceana Wong
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
Quarter 3 lesson 2 of English Grade 8.pptx
Time Series Analysis - Least Square Method Fitting a Linear Trend Equation
Screening and Selecting Studies for Systematic Review Dr Reginald Quansah
The hidden treasures Grade 5 Story with Motive Questions.pptx
Chapter 3. Pharmaceutical Aids (pharmaceutics)
DEPED MEMORANDUM 089, 2025 PMES guidelines pptx
kklklklklklklklk;lkpoipor[3rjdkjoe99759893058085
Plant Breeding: Its History and Contribution
LYMPHATIC SYSTEM.pptx it includes lymph, lymph nodes, bone marrow, spleen
AI and ICT for Teaching and Learning, Induction-cum-Training Programme, 5th 8...
A Presentation of PMES 2025-2028 with Salient features.pptx
What are New Features in Purchase _Odoo 18

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