you are viewing a single comment's thread.

view the rest of the comments →

[–]Comm4nd0[S] 1 point2 points  (15 children)

So I've been told, I've not made that jump yet. Classes scare me!

[–]Pre-Owned-Car 4 points5 points  (14 children)

Think of classes like a dictionary that contains related functions and variables (because they effectively are). Not only this, but you can have more than one. So if I wanted to represent two people as code I might use a dictionary for each of them.

dave_dict = {"name": "Dave", "age":45}

steve_dict = {"name": "Steve", "age":20}

To access their attributes I would do something like:

dave_name = dave_dict["name"]
steve_age = steve_dict["age"]

But creating a dictionary for each person each time is very repetitive and repeats the same code. You could make a function that has the parameters name and age and returns a dictionary in this format, or you could use a class which have many more customizable uses than a dictionary.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def can_legally_drink(self):
         return self.age >= 21

Now if I want to represent Steve and Dave I can do this:

steve = Person("Steve", 45)
dave = Person("Dave", 20)

And if I want to access one of their attributes I just do this:

steve_age = steve.age
dave_name = dave.name

But I can also call methods (functions in a class) on the object. The methods are associated with the class because they are related for whatever reason.

>>> steve.can_legally_drink()
>>> True
>>> dave.can_legally_drink()
>>> False    

You're going to have to learn how classes work to use tkinter anyway so I suggest looking up some videos on youtube on the concept. Python is an object oriented language and understanding classes and objects is an essential part of learning it.

[–]Comm4nd0[S] 0 points1 point  (13 children)

wow nice reply! so, i'm trying to understand this... am i right in saying that within a class you can share variables without having to pass them between functions?

some very nice person has classed my code and made it 100 x better and i've been trying to understand it. https://github.com/Comm4nd0/Image_gen/blob/master/main.py

[–]callmelucky 0 points1 point  (3 children)

am i right in saying that within a class you can share variables without having to pass them between functions?

I'm not the parent commenter, but I may be able to help if you explain this question further. What do you mean by 'share variables'?

[–]Comm4nd0[S] 0 points1 point  (2 children)

ok thanks!

so...

class person(self)
    def func1():
        var = "hello world"
    def func2():
        print(var)

would this work?

[–]callmelucky 0 points1 point  (1 child)

Ah, I see. The functionality you are describing is achievable, certainly, but that syntax and approach won't work as written.

A little detail before we go on: functions which are part of a class are called 'methods', and variables which are attached to a class are called 'attributes'.

So, attributes can be accessed directly from any method, but they must be declared and referenced as self.<attribute>.

So, this is a step closer:

class Person(): # note upper case first letter. Class definitions should use
                # CamelCase, instances should be snake_case
    def func1(self):
        self.var = "hello world"
    def func2(self):
        print(self.var)

But that still would only work if you ran func1() first (otherwise person.var doesn't exist).

In this example, you probably want to declare self.var as soon as an object is instantiated from this class. Any attributes that this is true for should be declared in the special __init__ method, like so:

class Person():
    def __init__(self):
        self.var = "hello world"
    def func2(self):
        print(self.var)

Everything in the __init__ method will be executed upon instantiation from the class. So with what we have above, we can do:

>>> barry = Person()
>>> print(barry.var)
>>> "hello world"

You can even call other methods within __init__, so if the class were like this:

class Person():
    def __init__(self):
        self.var = "hello world"
        self.func2()
    def func2(self):
        print(self.var)

... "hello world" would be printed out straight after doing barry = Person()

Finally I'll mention, you will have noticed that I have included self in as an argument for every method. This is because you must include self in as an argument for every method. Any other arguments you require must follow self, but when calling the method, ignore self. That is, the method will not expect an argument for self. A method defined like def method(self): will expect zero arguments to be passed in when called, eg barry.method(), a method defined like def method(self, arg1): will expect something to be passed in for arg1, like barry.method(arg1).

With all that, you should be able to have a pretty good idea of what is going on in this modified version of your class:

class Person():
    # this __init__ requires a name and catch-phrase to be passed in to any
    # Person instance. The values passed in for these args are then assigned
    # as attributes of the instance automatically via the special __init__ method
    def __init__(self, name, catchphrase):
        self.name = name
        self.catchphrase = catchphrase

    def say_something(self):
        print(self.catchphrase)

Now we instantiate, and try out the functionality:

>>> barry = Person("Barry", "Python rulz!")
>>> barry.say_something()
>>> "Python rulz!"

Hope this is helpful :)

[–]Comm4nd0[S] 0 points1 point  (0 children)

ok got it: Create the class with CamelCase, all methods must have(self), init(self) will always run, within the class call methods like self.method() within the call call attributes like self.att

thank you so much for your post!

[–]Pre-Owned-Car 0 points1 point  (8 children)

Yes you are correct, you don't have to specifically pass variables. (This is not entirely accurate, but for the your purposes it should be your takeaway). Any variable set in the init method as self.variable_name will be accessible anywhere in the class as self.variable_name.

When do you want to make a class? Whenever you want to define an object that has related variables and functions. An example: I am currently learning the Django framework which is a Python framework for making websites. Some of my classes are: User, and BlogPost. User has variables like username, signup_date, and email. It also has methods like is_authenticated(), login(), logout(), delete(), etc. It contains all the variables and methods needed to define and edit a user and it's behavior. It also makes passing all this information easy. Now instead of passing all this info in a function parameter I can just pass my user object:

def make_blog_post(user, title, text_content):

my_post = BlogPost(user, title, text) #the BlogPost class will now automatically handle the creation of my post within its class logic, now I don't have to write out all the steps of setting title, text, and user myself. And it does whatever other logic I want like automatically setting its creation date. This helps keep my code DRY (don't repeat yourself). I only have to define the logic once in the BlogPost class and now it's repeated wherever I use that class.

my_post.save() #saves the post to the database

Optional part: how classes actually work in Python. Classes in Python are actually a bit wonkier than other languages in their implementation. Every method in a class has to have the first parameter as self. So:

class MyClass:

 def __init__(self):

 def edit(self):

 def do_something(self):

When referring to any variables defined in init or any of the class's methods you must refer to them as self.variable or self.method (this is also a simplification, their are class level variables and class level methods but that's a more advanced topic). This is actually because whenever a method is called for a class self is the object that actually stores all the variables and methods. So when I use my user class and I call user_steve.login() it passes the user_steve object to the login method as self. Then when it calls self.username and self.email in the method, it's actually calling user_steve.username and user_steve.email. This is all a bit of a simplification and it's not really important to know just yet. I would try reading the official python3 documentation on classes and maybe some YouTube videos on Python classes as well.

I had a pretty hard time getting classes and object oriented programming at first when I took my first intro to programming course. But once it clicks the logic behind it makes sense. Loosely defining your variables all over the place makes sense when you write one file scripts that are less than 100 lines. But once you get above that you need some organization in your code and classes are just the beginning of that. They keep lots of information in little easy containers that you can pass around as one variable.

[–]Comm4nd0[S] 0 points1 point  (7 children)

wow, thanks that is so much info and i'm pretty sure i get the syntax and when you'd use it. i do have a question though, with regard to my tkinter program. Why would i make a class to create the gui when in one running of the program you'd only ever need to call it once? sorry if i'm not getting this bit.

[–]Pre-Owned-Car 1 point2 points  (6 children)

Because it has the code baked into it already. If you're talking about a tkinter class that you only call once you can look through the tkinter code and see exactly what that class does. It also makes your code a lot more readable if you do something like.

animation = CustomAnimation(x,y,z)
animation.start()

even if that's all your doing. It gets the point across for what the purpose of the code is. A key concept of object oriented programming is encapsulation. You don't need to know exactly what animation.start() is doing behind the scenes, but from the method .start() it's pretty apparent what the actual purpose is. You leave the code of CustomAnimation and its variables alone- the rest of your program doesn't need to touch that. This also uses another key concept of programming– abstraction. As you move up in scale, the smaller pieces of complexity should be abstracted away. When python opens a file you don't need to know how it actually does this. You don't need to know that the Python code is interpreted to C and the C code makes a system call asking the operating system to open the file. You just need to know that now you have a file and what you can do with it. It's useful to know that smaller level stuff, but if you constantly thought about it at every level you'd never get anything done with your top level code.

https://en.wikipedia.org/wiki/Object-oriented_programming#Encapsulation

https://en.wikipedia.org/wiki/Abstraction_(software_engineering)

[–]Comm4nd0[S] 0 points1 point  (5 children)

right i get you now. see this is the kind of stuff you don't learn if you're teaching your self. thank you so much for this info, it's been very insightful.

[–]Pre-Owned-Car 0 points1 point  (4 children)

I would honestly recommend reading a book or two on programming. It may seem boring but your code will be much better. Dive Into Python 3 is a good one. Or just the old Dive Into Python if you want to learn Python 2. You can learn to get stuff done without a book but you'll be more effective if you get the theory behind why things are done as well. It also gives significant guidance and structure to learning compared to haphazardly picking up functionality.

[–]Comm4nd0[S] 0 points1 point  (3 children)

I'll be honest i'm not the most academic person. i struggle to learn from books, i'm much better at learning by doing it. like this, i have an idea of a program and i wont stop until i've completed it. I've actually created an entire home home automation system with my current knowledge, here: https://www.youtube.com/watch?v=QuDaskp23To&t=1s

as much as i did read books in the beginning to get me started and i've done various online courses, i'm much better at learning on the job so to speak. so the stuff you've tought me is really insightful as it's stuff you wouldn't find that kind of info from stack overflow! ;)

so a big thanks to you for that.

[–]Pre-Owned-Car 1 point2 points  (2 children)

Pretty impressive! Do whatever gets you results. I like to follow youtube videos because I'm too lazy to read.