Jump to content

Can anybody help me understand classes in python

steelo

So, Im attempting to learn python and have watched countless videos on defining and using classes. I believe its referred to as object oriented programming. However, I cannot for the life of me grasp this concept or why it is vital to programming.

 

Would anybody be willing to give a newbie a python 101 explanation on how and why its used? Thanks!

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Slottr said:

It's an extremely easy way to manage and organize data structures

Ok...so, from what I understand you use it to define data within a variable. For example...set x to a class where, say name=Tom, Age=30, Weight=160. So when you call that variable, you can pull that data....this is my simplistic understanding of it

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, steelo said:

Ok...so, from what I understand you use it to define data within a variable. For example...set x to a class where, say name=Tom, Age=30, Weight=160

Like, yes

 

But it's an efficient way to organize that data, and reuse those types of forms

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Slottr said:

Like, yes

 

But it's an efficient way to organize that data, and reuse those types of forms

So a class is like a blank template you put data in? Do you ever perform calculation inside of a class?

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, steelo said:

So the class is like a template you put data in?

It can be, yeah

 

You can use it many different ways. Depends what the project is

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, Slottr said:

It can be, yeah

 

You can use it many different ways. Depends what the project is

Thank you for the explanation...Obviously, I need more time learning this. How is this different than passing variables to a function?

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, steelo said:

Thank you for the explanation...so why would you use a class instead of a function where you can pass variables?

Easy reuse of data structures, organization, inter-connectivity of things, etc. Again, it depends on the project

 

If you want to seriously learn more about OOP with python, read this:

https://www.amazon.ca/Learning-Python-Powerful-Object-Oriented-Programming-ebook/dp/B00DDZPC9S/ref=sr_1_5?keywords=object+oriented+programming+python&qid=1590111316&sr=8-5

 

It runs through things very well

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

If you know about struct in c or cpp, then this reply may help you.

 

Classes are just like modified form of struct. Basically a struct where you can add methods(functions), make a variable public or private, add prperty etc

Link to comment
Share on other sites

Link to post
Share on other sites

5 hours ago, Priyansh_Singh said:

If you know about struct in c or cpp, then this reply may help you.

 

Classes are just like modified form of struct. Basically a struct where you can add methods(functions), make a variable public or private, add prperty etc

I am fairly new to programming...I know the basics of sql and have learned visual basic and qbasic back in the 90's, which isn't even used any more. It's been a long time 😃 

 

I've read that learning classes/oop isn't a necessity if all you write are shorter, simpler programs. However, I'd like to learn the in's and outs of python over time. I enjoy tinkering with rpi's as a hobby and it would be a good marketable skill to learn. I'm not expecting to pick everything up in 3 days. I've taken a 1 week online course and have watched several how-to youtube videos on the basic concepts. As of right now, I am able to construct VERY simple programs but I'm sure it takes me 4 times as long as an experience programmer. So far, I think I have a pretty good grasp on variable casting, user input, calculations, while and for loops, if then statements and creating basic functions. I'd eventually like to learn machine learning/AI concepts, but it's going to be awhile before I'm to that point...

Link to comment
Share on other sites

Link to post
Share on other sites

15 hours ago, steelo said:

I am fairly new to programming...I know the basics of sql and have learned visual basic and qbasic back in the 90's, which isn't even used any more. It's been a long time 😃 

 

I've read that learning classes/oop isn't a necessity if all you write are shorter, simpler programs. However, I'd like to learn the in's and outs of python over time. I enjoy tinkering with rpi's as a hobby and it would be a good marketable skill to learn. I'm not expecting to pick everything up in 3 days. I've taken a 1 week online course and have watched several how-to youtube videos on the basic concepts. As of right now, I am able to construct VERY simple programs but I'm sure it takes me 4 times as long as an experience programmer. So far, I think I have a pretty good grasp on variable casting, user input, calculations, while and for loops, if then statements and creating basic functions. I'd eventually like to learn machine learning/AI concepts, but it's going to be awhile before I'm to that point...

Here  Is the link

 

from here i started to learn python ,

Python was my first programming language and i started to learn from here. This channel has a complete playlist on Python 

 

Hope it helps:)

Link to comment
Share on other sites

Link to post
Share on other sites

@steelo

You can think of it as a blueprint. A class defines the data and functions that can access and modify that data. It's a way to organize and brake the code down into smaller manageable chunks. Python doesn't enforce encapsulation (doesn't prevent accessing fields from outside) but by prefixing a variable name with an underscore you could indicate that it's a protected field and it shouldn't be modified from outside.

 

import datetime

class Human(object):
    def __init__(self, name, year_of_birth):
        self.name = name
        self._year_of_birth = year_of_birth
        self._health = 100

    # computed property
    @property
    def age(self):
        return datetime.datetime.now().year - self._year_of_birth

    # get property with validation
    @property
    def health(self):
        print(" -> helth get call")
        if self._health < 0 or self._health > 100:
            raise ValueError("health must be between 0 and 100")
        return self._health

    # set with validation
    @health.setter
    def health(self, value):
        print(" -> helth set call")
        if value < 0 or value > 100:
            raise ValueError("health must be between 0 and 100")
        self._health = value;
 
    def greet(self):
        print("Hello " + self.name + "!")
        
 mike = Human("Mike", 1990)
print(mike.age)		# works fine
mike.age = 20		# will throw error because age setter isn't defined

If a value is restricted to an interval lets say health must be between 0 and 100 it might be a good idea to enforce it. In the code you can see that the health is validated at every get/set call.

mike.health -= 1	# getter and setter called so the input is validated
mike.health = 420 	# will throw value error
mike._health = -10 	# allowed but it's a red flag
print(mike.health) 	# value error

A class is like a single cell organism. Relatively simple on it's own, It can interact with the outside but protected by a cell wall.

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, shadow_ray said:

@steelo

You can think of it as a blueprint. A class defines the data and functions that can access and modify that data. It's a way to organize and brake the code down into smaller manageable chunks. Python doesn't enforce encapsulation (doesn't prevent accessing fields from outside) but by prefixing a variable name with an underscore you could indicate that it's a protected field and it shouldn't be modified from outside.

 


import datetime

class Human(object):
    def __init__(self, name, year_of_birth):
        self.name = name
        self._year_of_birth = year_of_birth
        self._health = 100

    # computed property
    @property
    def age(self):
        return datetime.datetime.now().year - self._year_of_birth

    # get property with validation
    @property
    def health(self):
        print(" -> helth get call")
        if self._health < 0 or self._health > 100:
            raise ValueError("health must be between 0 and 100")
        return self._health

    # set with validation
    @health.setter
    def health(self, value):
        print(" -> helth set call")
        if value < 0 or value > 100:
            raise ValueError("health must be between 0 and 100")
        self._health = value;
 
    def greet(self):
        print("Hello " + self.name + "!")
        
 mike = Human("Mike", 1990)

print(mike.age)		# works fine
mike.age = 20		# will throw error because age setter isn't defined

If a value is restricted to an interval lets say health must be between 0 and 100 it might be a good idea to enforce it. In the code you can see that the health is validated at every get/set call.


mike.health -= 1	# getter and setter called so the input is validated
mike.health = 420 	# will throw value error

mike._health = -10 	# allowed but it's a red flag
print(mike.health) 	# value error

A class is like a single cell organism. Relatively simple on it's own, It can interact with the outside but protected by a cell wall.

Thank you...I sat down yesterday, typed out the code examples I found online (even though I didnt fully understand it) and played around with it, changing and editing. From my understanding, it makes assigning/pulling data easier and code a lot more organized. If you have a team of programmers working on separate modules, its easier for them to access a variable without having to hunt for what another programmer named it.

 

Now, I realize sometimes you have to import 'tools' or libraries....like 'time' if you want to use the sleep() function. Are these just classes somebody else created?

 

Link to comment
Share on other sites

Link to post
Share on other sites

9 hours ago, Priyansh_Singh said:

Here  Is the link

 

from here i started to learn python ,

Python was my first programming language and i started to learn from here. This channel has a complete playlist on Python 

 

Hope it helps:)

I've been watching these same videos while exercising 🙂After I watched (and finished exercising), I practiced some of his examples on my rpi using mu...

Link to comment
Share on other sites

Link to post
Share on other sites

56 minutes ago, steelo said:

I've been watching these same videos while exercising 🙂After I watched (and finished exercising), I practiced some of his examples on my rpi using mu...

Did you tried video of this channel. If not I highly recommend to watch videos of this channel. 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Priyansh_Singh said:

Did you tried video of this channel. If not I highly recommend to watch videos of this channel. 

Yes, Ive been watching about 30 mins a day while I ride my stationary bicycle 😁

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, steelo said:

Yes, Ive been watching about 30 mins a day while I ride my stationary bicycle 😁

What type of material you really want ??

Or on what topic ??

Link to comment
Share on other sites

Link to post
Share on other sites

21 minutes ago, Priyansh_Singh said:

What type of material you really want ??

Or on what topic ??

Just general programming/python concepts right now to gain an understanding of the fundamentals...would like to eventually use it for my raspberry pi to control lights, sensors and motors...also, it would be a wonderful marketable skill to learn for the workplace.

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, steelo said:

If you have a team of programmers working on separate modules, its easier for them to access a variable without having to hunt for what another programmer named it.

It helps in personal projects too. Just try to modify code you wrote 2 or 3 weeks ago. :D

 

5 hours ago, steelo said:

Now, I realize sometimes you have to import 'tools' or libraries....like 'time' if you want to use the sleep() function. Are these just classes somebody else created?

That's an interesting question. As far as I know, yes you can use classes and functions defined in other files. In this case with time.sleep() the answer a  little bit complicated. Python is based on C, the interpreter and the built in modules were written in C, including the sleep method. And it's OS dependent.

 

For example on windows (at the really end of the timemodule.c file) there are a few system calls trough Synchapi.h. It calls the WaitForSingleObjectEx or the Sleep() functions to halt code execution.

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

59 minutes ago, shadow_ray said:

It helps in personal projects too. Just try to modify code you wrote 2 or 3 weeks ago. :D

 

That's an interesting question. As far as I know, yes you can use classes and functions defined in other files. In this case with time.sleep() the answer a  little bit complicated. Python is based on C, the interpreter and the built in modules were written in C, including the sleep method. And it's OS dependent.

 

For example on windows (at the really end of the timemodule.c file) there are a few system calls trough Synchapi.h. It calls the WaitForSingleObjectEx or the Sleep() functions to halt code execution.

Thanks, that was an interesting read...so, is a module (like sleep) kind of like a mini program you import, (which may have classes, objects itself)?

 

I've been using a rpi to learn and have read that there are subtle differences in some things...like 'clear' in linux and 'cls' in windows to clear the screen.

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, steelo said:

Thank you...I sat down yesterday, typed out the code examples I found online (even though I didnt fully understand it) and played around with it, changing and editing. From my understanding, it makes assigning/pulling data easier and code a lot more organized. If you have a team of programmers working on separate modules, its easier for them to access a variable without having to hunt for what another programmer named it.

 

Now, I realize sometimes you have to import 'tools' or libraries....like 'time' if you want to use the sleep() function. Are these just classes somebody else created?

 

That's pretty much it, it's mostly about organising code. I think the best way to describe classes is to show what things would look like without them (I don't use python a huge amount, so the code here many not be perfect, but should hopefully illustrate the points).

 

Lets say that you wanted to represent a person. You might have something like

person_first_name = "John"
person_last_name = "Smith"
person_birthday = "1978-01-30"
person_age = 42

def person_print_name(first_name, last_name):
    print(first_name + " " + last_name)
    
person_print_name(person_first_name, person_last_name)

this sort of works, but it means that you need to keep track of all of those variables for one conceptual thing, and have to pass all of them around to everything that wants to use a person - the function signatures are going to get really messy. If you decide that a person should also have a middle name, a lot of code changes are required to keep track of all the new property and pass it around.

 

We can solve that by collecting all of the data together into a single object - a class

class Person:
    def __init__(self, first_name, last_name, birthday, age):
        self.first_name = first_name
        self.last_name = last_name
        self.birthday = birthday
        self.age = age
        
def person_print_name(person):
    print(person.first_name + " " + person.last_name)
    
person = Person("John", "Smith", "1978-01-30", 42) # The self argument is implicit
person_print_name(person)

Now it's much easier to pass this one thing around rather than a bunch of different variables. If we want to add a middle name, we need to change how we construct the person (there's no getting away from that), but we don't have to change everywhere that just passes around a person.

 

We can do even better though. person_print_name is part of the behaviour of a person, so it would make sense for it to be a method of a person. A method is just a function that is attached to a particular object, so that you keep all of the behaviour that affects a given object in one place.

class Person:
    def __init__(self, first_name, last_name, birthday, age):
        self.first_name = first_name
        self.last_name = last_name
        self.birthday = birthday
        self.age = age
        
    def print_name(self):
        print(self.first_name + " " + self.last_name)
    
person = Person("John", "Smith", "1978-01-30", 42)
person.print_name() # self is set to the object that you called the method on, which is `person` here

Methods can also edit the person, and this can be really helpful when you want to make sure some things are always true in your object. For example, we want to make sure that the age matches the birthday, and that it makes sense

class Person:
    def __init__(self, first_name, last_name, birthday):
        self.first_name = first_name
        self.last_name = last_name
        self.set_birthday(birthday)
        
    def print_name(self):
        print(self.first_name + " " + self.last_name)
        
    def set_birthday(self, birthday):
        if birthday > today:
            raise Exception("You can only use this class with people who have already been born")
        self.birthday = birthday
        self.age = years_since(birthday)
    
person = Person("John", "Smith", "1978-01-30")
person.set_birthday("2020-05-23")

In python, it's still possible to just do person.age = -1 to bypass this check, but in many other languages you can make some fields private so they can only be accessed by methods of the current class.

 

Classes have other functionality too, like static methods (methods that are associated with the class but not a specific object, so they don't get a self argument, so the only benefit is that they are kept together with the other code relating to that class), and inheritance (which means you can have multiple child classes (such as Child and Adult) that share all of the code from a parent class (Person), but can also provide their own functionality or even override functionality from the parent class). They are slightly more advanced concepts, so I won't go into them here for now, but I'm happy to explain them it a bit more detail if you're interested.

HTTP/2 203

Link to comment
Share on other sites

Link to post
Share on other sites

Thank you for the good explanation. Ive been finding simple examples online, editing and adding to it and its really starting to make sense now.

 

Before really sitting down and attempting to learn python, I glanced at some code and thought...what the heck is the point of assigning person=self.person. (I think thats how they wrote it) now I see how rather than pass 15 variables between functions, you can call them at any time without even knowing the variable names or you can assign values.

Link to comment
Share on other sites

Link to post
Share on other sites

30 minutes ago, colonel_mortis said:

That's pretty much it, it's mostly about organising code. I think the best way to describe classes is to show what things would look like without them (I don't use python a huge amount, so the code here many not be perfect, but should hopefully illustrate the points).

 

Lets say that you wanted to represent a person. You might have something like


person_first_name = "John"
person_last_name = "Smith"
person_birthday = "1978-01-30"
person_age = 42

def person_print_name(first_name, last_name):
    print(first_name + " " + last_name)
    
person_print_name(person_first_name, person_last_name)

this sort of works, but it means that you need to keep track of all of those variables for one conceptual thing, and have to pass all of them around to everything that wants to use a person - the function signatures are going to get really messy. If you decide that a person should also have a middle name, a lot of code changes are required to keep track of all the new property and pass it around.

 

We can solve that by collecting all of the data together into a single object - a class


class Person:
    def __init__(self, first_name, last_name, birthday, age):
        self.first_name = first_name
        self.last_name = last_name
        self.birthday = birthday
        self.age = age
        
def person_print_name(person):
    print(person.first_name + " " + person.last_name)
    
person = Person("John", "Smith", "1978-01-30", 42) # The self argument is implicit
person_print_name(person)

Now it's much easier to pass this one thing around rather than a bunch of different variables. If we want to add a middle name, we need to change how we construct the person (there's no getting away from that), but we don't have to change everywhere that just passes around a person.

 

We can do even better though. person_print_name is part of the behaviour of a person, so it would make sense for it to be a method of a person. A method is just a function that is attached to a particular object, so that you keep all of the behaviour that affects a given object in one place.


class Person:
    def __init__(self, first_name, last_name, birthday, age):
        self.first_name = first_name
        self.last_name = last_name
        self.birthday = birthday
        self.age = age
        
    def print_name(self):
        print(self.first_name + " " + self.last_name)
    
person = Person("John", "Smith", "1978-01-30", 42)
person.print_name() # self is set to the object that you called the method on, which is `person` here

Methods can also edit the person, and this can be really helpful when you want to make sure some things are always true in your object. For example, we want to make sure that the age matches the birthday, and that it makes sense


class Person:
    def __init__(self, first_name, last_name, birthday):
        self.first_name = first_name
        self.last_name = last_name
        self.set_birthday(birthday)
        
    def print_name(self):
        print(self.first_name + " " + self.last_name)
        
    def set_birthday(self, birthday):
        if birthday > today:
            raise Exception("You can only use this class with people who have already been born")
        self.birthday = birthday
        self.age = years_since(birthday)
    
person = Person("John", "Smith", "1978-01-30")
person.set_birthday("2020-05-23")

In python, it's still possible to just do person.age = -1 to bypass this check, but in many other languages you can make some fields private so they can only be accessed by methods of the current class.

 

Classes have other functionality too, like static methods (methods that are associated with the class but not a specific object, so they don't get a self argument, so the only benefit is that they are kept together with the other code relating to that class), and inheritance (which means you can have multiple child classes (such as Child and Adult) that share all of the code from a parent class (Person), but can also provide their own functionality or even override functionality from the parent class). They are slightly more advanced concepts, so I won't go into them here for now, but I'm happy to explain them it a bit more detail if you're interested.

Very cool, thank you!

 

Should I get into the habit of creating classes when I code?

Link to comment
Share on other sites

Link to post
Share on other sites

54 minutes ago, steelo said:

Very cool, thank you!

 

Should I get into the habit of creating classes when I code?

Classes aren't always the answer, and overusing them can make code messy, but if you have groups of data that belong to the same "thing", and that data is being passed around between functions, then classes are good.

 

You may find it difficult at first to decide what should be a class and what shouldn't - it's one of those things where you just need to try it a few times and it will start to feel more natural. The test for whether a class was a good addition is whether it makes the code easier to read or navigate.

HTTP/2 203

Link to comment
Share on other sites

Link to post
Share on other sites

40 minutes ago, colonel_mortis said:

Classes aren't always the answer, and overusing them can make code messy, but if you have groups of data that belong to the same "thing", and that data is being passed around between functions, then classes are good.

 

You may find it difficult at first to decide what should be a class and what shouldn't - it's one of those things where you just need to try it a few times and it will start to feel more natural. The test for whether a class was a good addition is whether it makes the code easier to read or navigate.

Great points! Thank you for taking the time to explain this to a newbie.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×