Objects and Classes in Python Programming

objects n.w
1 / 22
Embed
Share

Discover the fundamentals of object-oriented programming in Python, exploring the concepts of objects, classes, and their significance. Learn how to create instances, initialize variables, and build a particle simulator using Python. Gain insights into the essential principles of object-oriented design for effective Python development.

  • Python Programming
  • Object-oriented
  • Classes
  • Python Libraries
  • Particle Simulator

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Objects CSEG Python Training, Week 6

  2. Python Objects Python is a flexible language that supports both object oriented and procedural programming models. Even though Python doesn t force you to write classes in your own code, an understanding of object oriented code is essential when working with Python s standard library as well as its external libraries. Technically everything in Python is an object. The language uses its syntax to hide those details from you most of the time, but you do have the ability to access those details if you need them.

  3. What Are Objects? Objects are collections of related data and routines that operate on that data. Put another way, objects have data and behavior. EX: A car can have a color, VIN, velocity, acceleration, etc. EX: A car can accelerate, brake, park, etc. Can have multiple instances of an object Each instance has its own copy of its data. EX: One car can be red and a different car can be blue.

  4. What Are Classes? Classes are a blueprint for constructing an object. That is, a class tells Python how to make an instance of an object. Classes can inherit from each-other. We won t be covering this today

  5. Particle Simulator Going to explore object concepts by writing a 1D particle simulator.

  6. empty_class.py Let s start with the simplest class possible for our particle: one that doesn t have any data or routines. We ll create an instance by calling the class name.

  7. particle_with_attributes.py Let s add a position and a velocity.

  8. The __init__ method Copy-pasting the initialization of our particle variables is tedious and error prone. We ll add an initialization method to our Particle class. Functions that belong to a class are called methods. If you create a method named __init__, it will be called when you create an instance of your class. __init__ can have as many arguments as you want, but the first one is called self. The self argument refers to the actual instance that is being initialized.

  9. particle_with_init.py

  10. Adding Methods We can initialize our particles now, so let s add some behaviour. We ll add a timestep that will move the position of our particle using our velocity. It would be nice to be able to print the position, so we ll add a method to do that too. All your methods need to start with the self argument.

  11. particle_move.py

  12. basic_type_copy.py

  13. object_reference.py

  14. Object References Variables that contain basic types (ints, floats, strings, bools) are always copied on assignment. All other variables in Python are object references. It s basically the memory location of the object and not the object itself. This means that any changes you make to an object propagate everywhere that has a reference to the same object. Takeaway: Any changes you make to an object inside a function propagate everywhere that has another reference to the object. In Fortran terms, variables that contain object references are always intent(inout). This is referred to as a side-effect Do your best to make it clear that a function will have a side-effect. Write your code so that it s safe to assume that a function won t have a side-effect unless indicated otherwise.

  15. Object Equality Generally, if you have two variables that are object references, they will only be equal(==) if they refer to the same object. However, several classes change this behavior so that the == operator can be used to determine if the data in two instances are the same. EX: datetime objects allow this to make them easier to use. This is achieved using a feature of classes known as operator overloading . We ll get to this later. Unless otherwise stated, assume that == only checks if two object references point to the same object.

  16. What If We Need 100 Particles? We could copy-paste the code to construct particles and then copy-paste our code to advance the timestep. Copy-paste is the fastest way to spread errors throughout your code. Finding errors in big blocks of repeated code is like playing Where s Waldo. Bloats your code, making it difficult to read in general. Remember: DRY(Don t Repeat Yourself) We need a data structure. Specifically, we need a list.

  17. Lists One of the data structures provided by Python. Similar to an array (but with important distinctions). One dimensional. Starts empty but allows you to add to it using the append method. Not homogenous, can contain any type of variable. EX: A single list is allowed to contain ints, floats, object references, etc. Although this is allowed, lists are typically used to store one type of variable. Usually instances are created by calling the class name, but lists are so common Python allows you to create a new empty list by simply using [] EX: empty_list = [] Those are the basics, but we ll go into more detail about lists later.

  18. particle_list.py

  19. When Is It A Good Idea To Write A Class? Object-oriented code isn t a replacement for procedural code, but can be used together. If you have several variables that make sense to group together but otherwise don t have behavior of their own, they can be grouped together into a class. However, Python has namedtuples and dataclasses to represent this concept in a more convenient/clear way. When your concept maps to the idea of a specific entity that has its own data and behavior. A car, a particle, a file, a tropical cyclone track. Complex data structures such as grids, trees, graphs, etc. The methods, generally, shouldn t need to be called in a specific order to be used correctly. A warning sign that something shouldn t be an object is if it just has __init__ and a single method.

  20. Homework 1. Create an empty class named Vector2D and create a couple of instances. 2. See what happens when you compare your two instances using the == operator. 3. Add an __init__ method to Vector2D that initializes it with an x and y variable. 4. Add a method to Vector2D named get_magnitude that computes and returns the magnitude of the vector. 5. Add a method to Vector2D named normalize that normalizes the x and y components of the vector so it has a magnitude of 1. 6. Write a function that takes a Vector2D instance, calls the normalize method on it, and then ends. This should normalize the Vector2D instance as a side-effect.

  21. Extra Credit 5. Create a list of 10 Vector2D objects with random x, y components. 6. Create a function that normalizes each Vector2D object in your list.

  22. Example Files You can get copies of the example files with the following command: git clone https://gitlab.com/CSU-CIRA/python_training_resources/objects.git You can also download them from here: https://drive.google.com/drive/folders/13Srm5cLIiHEuh0Eva5d7IDgAVW3xrqUw?usp=sharing

More Related Content