Python Forum
Help | Classes to use in real world
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help | Classes to use in real world
#1
Hi guys,

Tutorials and youtube videos often teach python classes using a person (and without real inputs). My question is, how can I take a module and write a program using classes? For example I would use Requests or bs4, etc...and write one program using classes. And I mean probably all those modules are written in a class, if it's already a class, how can I write a class from already a class?

I've been searching videos and posts about Classes but couldn't find a tutorial or sample in using classes in real life. Can anyone shed some light onto this?

Thanks and appreciate the inputs!
Reply
#2
soothsayerpg Wrote:couldn't find a tutorial or sample in using classes in real life. Can anyone shed some light onto this?

I think you're taking the problem the wrong way round. Try to solve a "real life" problem first, then see how classes can help you. Classes can be used almost everywhere in the code. If you post one of your programs here, we can give you ideas to add classses to this program.
Reply
#3
Maybe start from fundamentals.

Python is object-oriented programming language. This means that (almost) everything in Python is object (Python glossary: object).

From Python documentation:

Quote:Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. /../ Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory./../

An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.

From description of built-in function type() we read:

Quote:With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

So object type is (essentially) it's class. You can check it:

>>> spam = list()
>>> type(spam)
list
>>> spam.__class__
list
As stated earlier, type (class) determines the operations that the object supports. You are familiar with built-in types (classes) like list, tuple, dictionary, string etc.

Class can be seen as template for creating objects. If you create object using class then it called instance of that class. In code above spam is instance of list class.

We take granted operations we can perform with instances of built-in classes like list and string. Self-defined class by itself is of no use unless there is some functionality associated with it. Functionalities are defined by setting attributes, which act as containers for data and functions related to those attributes. Those functions are called methods (sorted(spam) is using built-in function on instance of list class, spam.sort() is using list class method on list class instance).

Python classes supports a full range of features, such as inheritance, polymorphism, and encapsulation. Getting things done in Python may require writing new classes and defining how they interact through their interfaces and hierarchies (but before you start create your own class make sure that there are not built-in types or types in built-in modules what have required functionality).

So you create class when you need to do something with data and existing types are not fitted for that. There can be many reasons to do that - you may want limited interfaces / limited functionality with interacting your object; you may want add specific methods etc, etc).

If you haven't encountered need to create classes then it's no problem. Understanding class fundamentals may help you better recognise situations when you may need class Smile
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
Here's an example of a simple script I made using PyAutoGui

import pyautogui as pag

pag.FAILSAFE=True

#Call Chrome
pag.hotkey('command', 'space')
pag.typewrite('Chrome\n', 0.25)
pag.moveTo(412, 81, duration=2)
pag.click(button='left')
pag.typewrite('target_site_example.com\n')
pag.moveTo(927, 431, duration=5)
pag.click(button='left')
pag.moveTo(286, 132, duration=5)
pag.click(button='left')
pag.click(button='left')
pag.moveTo(1206, 946, duration=5)
pag.click(button='left')
pag.moveTo(1797, 587, duration=5)
pag.click(button='left')

pag.moveTo(768, 137)
pag.click(button='left')

# #Scrolling to second section
pag.scroll(-50)

# #Scrolling and click to sort rankings
pag.moveTo(1189, 735, duration=5)
pag.click(button='left')

# # Fire up Nimbus
pag.moveTo(1146, 84, duration=5)
pag.click(button='left')

# # Screenshot Entire Page
pag.moveTo(995, 331, duration=5)
pag.click(button='left')
What I meant was how can I wrote that in a Class kind of fashion? As I am really a bit confused since that module is already a class, what's the point in making a Class off of a already Class. And yes, I can't get my head around on how can I construct it to Class. How you guys that are well-rounded in Python can make a Class type script from that module?

Also, since I've mentioned they are all (probably most are written in Class) so whenever we create one then we always call's for inheritance, right?

If you can make that script I had wrote to a class and include in your response, that would be very, very helpful to me to study on how you guys construct a Class off of something/module.

Thanks for the response @Gribouillis & @perfringo
Reply
#5
In this example, you could start using a class to decompose the different actions into smaller units with an expressive name. I don't understand all the code because I don't use pyautogui, but you could start from here
import pyautogui as pag

class Agent:
    def run(self):
        """Main agent's action"""
        self.call_chrome()
        self.scroll_to_second_section()
        self.click_to_sort_ranking()
        self.fire_up_nimbus()
        self.screenshot_page()
    
    def call_chrome(self):
        # TODO: decompose this into smaller units
        pag.hotkey('command', 'space')
        pag.typewrite('Chrome\n', 0.25)
        pag.moveTo(412, 81, duration=2)
        pag.click(button='left')
        pag.typewrite('target_site_example.com\n')
        pag.moveTo(927, 431, duration=5)
        pag.click(button='left')
        pag.moveTo(286, 132, duration=5)
        pag.click(button='left')
        pag.click(button='left')
        pag.moveTo(1206, 946, duration=5)
        pag.click(button='left')
        pag.moveTo(1797, 587, duration=5)
        pag.click(button='left')
        
        pag.moveTo(768, 137)
        pag.click(button='left')
        
    def scroll_to_second_section(self):
        pag.scroll(-50)
        
    def click_to_sort_ranking(self):
        pag.moveTo(1189, 735, duration=5)
        pag.click(button='left')
        
    def fire_up_nimbus(self):
        pag.moveTo(1146, 84, duration=5)
        pag.click(button='left')
        
    def screenshot_page(self):
        pag.moveTo(995, 331, duration=5)
        pag.click(button='left')

if __name__ == '__main__':
    pag.FAILSAFE=True
    a = Agent()
    a.run()
Of course, it's only the beginning.
Reply
#6
Thanks @Gribouillis. That class example would definitely be helpful to me. Been a week thinking on how to make a script and remake it to a class.

Are we obligated to use each and every class section whenever we construct a class, you know, instance attribute/method, class attribute/method, inheritance, etc. etc...? Or just what we need?

I see you didn't use declare
__init__
instance and why didn't you declare inheritance on your Class from PyAutoGui?
Reply
#7
soothsayerpg Wrote:Are we obligated to use each and every class section whenever we construct a class
No of course not. There are small classes that use only a small part of class features.
soothsayerpg Wrote:why didn't you declare inheritance on your Class from PyAutoGui?
Why would I? I don't even know if PyAutoGui is a class. Use inheritance only if you have a very good reason to do so. As you are a beginner, start with simple classes.
Reply
#8
(Jul-06-2019, 09:27 AM)soothsayerpg Wrote: Are we obligated to use each and every class section whenever we construct a class, you know, instance attribute/method, class attribute/method, inheritance, etc. etc...? Or just what we need?
Just what you need,it all depend on how class in made.
Now all automation run at once when call run method.
A alternative for separate calls could be:
import pyautogui as pag

class Agent:
    pag.FAILSAFE=True

    @property
    def call_chrome(self):
        # TODO: decompose this into smaller units
        return 'Run chrome automation'

    @property
    def scroll_to_second_section(self):
        return 'scroll 50'
Use:
>>> auto = Agent()

>>> auto.call_chrome
'Run chrome automation'
>>> auto.scroll_to_second_section
'scroll 50'
Think of __init__ as carrier of data from outside of class that want to bring in when create object auto(in this case).
Most the automation call you have is pre-defined with values that i guess you have tested.

Just a example of two ways to bring in data from outside.
import pyautogui as pag

class Agent:
    def __init__(self, move_x, move_y):
        self.move_x = move_x
        self.move_y = move_y

    @property
    def call_chrome(self):
        #pag.moveTo(self.move_x, self.move_y, duration=2)
        return self.move_x, self.move_y

    def scroll_to_second_section(self, value):
        #pag.scroll(value)
        return value
Use:
>>> auto = Agent(50, 100)
>>> 
>>> auto.call_chrome
(50, 100)
>>> auto.scroll_to_second_section(-200)
-200
Reply
#9
If your interested in comparisons of no class use VS class use i have modified a couple programs in tutorials to modify a program to use classes. In that case you can see the transformation and how cluttered and unorganized the non-class code is.

At the very bottom of the original post is a comparison of sentdex code (not using classes) to the bottom code (the same code using classes). Both accomplish the same task, but different organization structures.
https://python-forum.io/Thread-PyGame-wa...-tutorials

In the pygame tutorials i convert basic global code into a Player class start building it beyond for more needs.
https://python-forum.io/Thread-PyGame-Lo...ets-part-2
In the beginning of the tutorial series the class is just a few lines, but at the end the player class expands to
https://github.com/metulburr/ShooterGame.../player.py

Although these examples do no utilize inheritance the labels in the same program does. In that example GameOverText and TopLeftText classes both make similar text labels. Why create separate font_init and make_text methods for each class when you can inherit it from a super class to reduce redundancy? THough this is a small example with 2 sub classes, it would make a lot more sense if you had 100 sub classes.
Recommended Tutorials:
Reply
#10
Honestly, the autogui thing is fine as is, without classes. Classes/objects are most useful when you have some sort of data or information that's tied to functionality.

In the real world, your wallet would be a class. It keeps track of what's in it (how much money, cards, etc), and it knows what to do with those things (give money, charge card, etc).

In a video game, a class could be your character. You have stats that are different per-character (strength, agility, etc) as well as carried items or equipment, and the character itself knows how to move or attack.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Hello World! rufenghk 0 933 Jun-02-2022, 09:48 PM
Last Post: rufenghk
  Very new to Python world daveseaman 0 1,453 Jun-25-2021, 07:17 PM
Last Post: daveseaman
  running python hello world Avarage_Joe 8 5,203 Apr-13-2018, 04:20 PM
Last Post: Avarage_Joe
  Hello world! program, window disappears nerio 3 5,568 Mar-16-2018, 07:03 PM
Last Post: knackwurstbagel
  Using classes? Can I just use classes to structure code? muteboy 5 4,978 Nov-01-2017, 04:20 PM
Last Post: metulburr
  'Hello, World!' Problem - Urgent OmarSinno 7 4,470 Sep-07-2017, 06:22 AM
Last Post: OmarSinno
  how to generate random 3d world (like minecraft) in python hsunteik 3 88,894 Jan-06-2017, 06:35 PM
Last Post: metulburr
  Hello World issues when using %% with ipython landlord1984 5 8,776 Dec-11-2016, 10:11 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020