Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
oop breaks
#1
I'm having difficulty grasping the idea behind oop. I'm at a stage where I can write working programs but when I separate states and activities into separate modules I get tripped up. I took the simplest program (that requires some user interactivity) I could think of. Extremely easy program:
#bottles0.py
bottles = int(input('How many bottles? '))
while True:
	print('bottle count: ', bottles)
	bottles -=1
	if bottles > 1:
		print('there are ', bottles ,' left.')
	elif bottles == 1:
		print('There is only ',bottles ,' left.')
	else:
		print('There are no more bottles left.')
		break
print('Happy Holidays!')
Now when I get into "proper" oop:
#bottleclass.py
class Bottles():
	def __init__(self):
		self.llist = []
	def many(self, num):
		print(num ,'bottles on the wall.')
		self.llist.append(num)
		num -=1
		return num
	def lower(self):
		for ll in self.llist.reverse():
			if ll == '1':
				print('there\'s', ll, 'bottle on the wall.')
			elif ll == '0': 
				print('there are no more bottles on the wall.')
			else:
				print('there are ',ll, 'bottles on the wall')
#bottles0run.py
from bottleclass import Bottles

B = Bottles()

while True:
	n = int(input('Starting bottles: '))
	if n == '0' or n =='':
		break
	else:
		B.many(n)
B.lower()
So it is an unmitigated disaster. How would I get this simple program in oop? What exactly is the advantage to oop style? - What will be the advantage when I get to the stage where I can make sense of it?
Reply
#2
classes contain logic and data together. Usually you would not have a Bottles class, but a Bottle class. This is because a class is to handle numerous objects.

So you might have
bottles = []
for i in range(100):
    bottles.append(Bottle)
where each bottle object might have different data. In the case of a bottle, each might have different colors, type of bottles, type of caps (screw cap/cork/pop cap), types of labels, etc. Each of this is the data. The logic being to unscrew a screw cap, and handle popping a pop cap, etc.

The advantage of OOP is that it is easier to maintain, and shorter code because you are re-using code. Then you have more advanced concepts such as inheritance.

Im assuming you have already googled how to make classes, just deciphering the purpose of it? In a real world example..... So think of a game where there are tons of enemies..like space invaders. Each enemy has a difficulty, appearance, movement, etc. This can be handled by one Enemy class with different data to determine which enemy it is and how it should behave. Instead of coding each enemy separately, it is all contained in that one enemy class. To draw each enemy you might just do
for enemy in enemies:
   enemy.draw()
and all the enemies are drawn to the screen based on what the draw method actually does. It doesnt matter if there are no enemeies shown, 1 enemy, or 1000 enemies. The same can be done for animation, behavior, appearance, etc. This all can add quite a bit of code to a class, which makes it easier to maintain when you say "I need to change the filename of the enemy class type X". That means you go to the enemy class to edit it. And so on and so on.

There is not a lot there in your example to put in a class. Usually you would never put a print() in a class. You would return the string and then print it. Same with input(), you would never take termmal input within a class, but pass that data to the class. But there is not much to put in a class that just asks the user input and prints out based on that input.
Recommended Tutorials:
Reply
#3
Quote:Classes contain logic and data together.
Can you elaborate...my apologies but this is difficult for me to get right now...

Quote:Usually you would not have a Bottles class, but a Bottle class.
Yes, but to be fair this was a very simple prog to understand how oop is different from a single file program.

Quote:Im assuming you have already googled how to make classes, just deciphering the purpose of it?
I understand classes. I can write them as well. The problem is that I can follow book & tutorial examples. I just can't get the hang of oop to write my own program from scrap. It seems that in oop you MUST have a crystal clear vision of what you want your program to do. Right now I just generalize the broader idea and throw code on 1 file. Then debug...

I also understand classes and inheritances such as class A < B, etc

Quote:you would never take termmal input within a class, but pass that data to the class.
You're right. I just can't figure out how to pass that data into the class... How do you generally pass data in regularly.
Reply
#4
class Bottle:
    def __init__(self, position):
        self.cap_status = position
    def open_cap(self):
        if self.cap_status == 'closed':
            self.cap_status = 'open'
            
btl = Bottle('closed')
The dunder init method (AKA __init__) is what executes when the object is created btl = Bottle('closed'). The dunder init method contains the data, while the open_cap method is the logic. the logic changes the data based on conditions. The string 'closed' gets passed to the class. This would be the input.

If you want, you can go through my pygame tutorials. These start out without OOP like almost all pygame tuts do, but then quickly add classes in when they are needed. You can see how the code looks before classes and how it transforms with classes. I also mid way though, shift code around and explain as i go that i am organizing it into a new class, etc. At the end I structure and move it all into classes and modules. I plan on making more tutorials that add states (menu/splash screen) that also utilize classes and inheritance to handle the states (as an alternate view point of usage of classes)

Also if you want to see a snippet of code before classes and after classes, i have a tutorial for bad structure here in which i purposely did the same thing but used OOP to make a point that OOP is much better.

Quote:I just can't get the hang of oop to write my own program from scrap. It seems that in oop you MUST have a crystal clear vision of what you want your program to do. Right now I just generalize the broader idea and throw code on 1 file. Then debug...
I think it takes a lot more effort to convert a program to OOP, than it is to write it in OOP from scratch. Once it is spaghetti code, its hard to unravel it. You can but it takes a long time.

Usually when i program i dont think of classes unless i know its going to be a class. Most of the time I will start picking stuff out of the main file and putting it into a new class to keep the main file short and clean. I seem to get writers block if i lay out the classes beforehand. It can take awhile before you are constantly thinking in terms of OOP when coding on the fly. I would start by always converting your code to OOP when needed. Its not Java... not everything has to be a class though. But the main idea is to not do a one file anymore. Always convert your code to OOP. At some point you wont need to convert, you just start writing in OOP.

Its mostly when you have multiple objects, but it can be when you are just using an attribute to bypass passing back and forth a variable or using the keyword global in functions. Sometimes global functions are so unwieldy that it makes sense to put them in a class and get rid of globals/passing vars back and forth. It might even take the effort of making a large project without classes with a need to maintain it, to even understand the purpose of classes unfortunately.
Recommended Tutorials:
Reply
#5
Quote:What exactly is the advantage to oop style? - What will be the advantage when I get to the stage where I can make sense of it?

There is a tremendous body of work to describe OOP as well as the advantages and disadvantages. The Java documentation covers a lot of the basic concepts here: https://docs.oracle.com/javase/tutorial/java/concepts/

The simple answer is that OOP enables programmers to implement remarkably complex systems in relatively small amounts of code. To get a sense of what you can do with it, you can also look at discussions about "design patterns" https://en.wikipedia.org/wiki/Software_design_pattern

I would also say that in my opinion, Python is not an ideal language to learn how to do OOP programming. With it's static typing and general OOP-focus, Java clearly illustrates the concepts.
Reply
#6
Quote:I would also say that in my opinion, Python is not an ideal language to learn how to do OOP programming.
That's a option i mean is really wrong Dodgy
The problem is that many try to write OOP in the same way in Python as done in Java.
This always lead to a lot more code than needed,
like using(getters/setters) and try to mix private and protected(which make no sense in Python).
Python Is Not Java
Reply
#7
(Dec-26-2017, 04:27 PM)snippsat Wrote:
Quote:I would also say that in my opinion, Python is not an ideal language to learn how to do OOP programming.
That's a option i mean is really wrong Dodgy
The problem is that many try to write OOP in the same way in Python as done in Java.
This always lead to a lot more code than needed,
like using(getters/setters) and try to mix private and protected(which make no sense in Python).
Python Is Not Java

The reason I don't like Python for teaching/learning OOP is that a language like Java is much more explicit and it's clear "what you're getting with OOP". In Python, you can do a lot of OOP and a new programmer can still ask "what am I getting with with OOP?"

Maybe I should have said it's not an ideal language for learning OOP concepts, instead of "programming".
Reply
#8
mpd, I can definitely see what you're saying, in that I think it's easier to teach OOP in a statically typed language rather than dynamically typed. That said, of the statically typed languages I know/knew (primary C, C++, Java and Scala) I'm not terribly impressed with them as languages to teach OOP. Each one has weird things, and though I like Scala, it has enough potential complexity to be difficult to teach with. So while I agree with your claim, I'm not impressed with the alternatives.

All that said, I have wondered if Python's type hinting might help here. I haven't really tried it, thought about it, or investigated "weird things" in Python's type hinting that would create any unnecessary confusion like I believe there are in the commonly used static languages.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tie Breaks klatlap 6 1,051 Mar-20-2023, 12:08 PM
Last Post: klatlap
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 1,949 Apr-05-2021, 05:40 PM
Last Post: deanhystad
  How to Remove Non-ASCII Characters But Leave Line Breaks In Place? bmccollum 4 4,256 Apr-09-2020, 07:59 PM
Last Post: DeaD_EyE
  Detect end of line in text file including line breaks DanielM 4 3,125 Dec-18-2019, 11:57 AM
Last Post: Malt
  Looping URLs breaks them PythonStudent 2 2,879 Apr-21-2018, 02:54 PM
Last Post: PythonStudent

Forum Jump:

User Panel Messages

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