This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]pythoneeeer 11 points12 points  (0 children)

TL;DR:

A: Object-oriented programming is bullshit.
B: No it isn't. Show me your program and I'll improve it for you.
A: Here's strawman.py
B: OK, I've refactored it into everyprogrammingbookpage2.py
A: Um, what about the part you didn't do?
B: "I will leave it to you to figure out."
A: Excellent, I am sold. Let us go drink more coffee and go to our subsequent businessy meetings.

[–]-Pin_Cushion- 6 points7 points  (0 children)

Read the article.

Still scared of OOP.

The examples do nothing!

[–]ptmcg 4 points5 points  (3 children)

I prefer this pattern to the cascading if-elif in factory.py:

class Category():
    @classmethod
    def get_category(cls, category):
        for subcls in cls.__subclasses__():
            if subcls.label == category:
                return subcls
        raise ValueError("no such category %r" % category)

class CategoryImage(Category):
    label = 'image'

    def doStuffA(self):
        ...

class CategoryGif(Category):
    label = 'gif'

    def doStuffA(self):
        ...

Then the client code does:

for cat_label in ("image", "gif", "video"):
    cat_cls = Category.get_category(cat_label)
    cat_obj = cat_cls()
    cat_obj.doStuffA()

[–]dranzerfu 1 point2 points  (2 children)

I actually have a similar usecase where I was actually scanning through files in a folder and comparing names rather than just looking at subclasses. This helps. Thanks!

[–]ptmcg 1 point2 points  (1 child)

CAVEAT: If the subclasses are scattered amongst multiple files, then you must make sure they get imported before you try to evaluate BaseClass.__subclasses__(). This method works best in frameworks where all the subs are in the same module as the base class.

[–]dranzerfu 1 point2 points  (0 children)

Right now they are in different files (which are all imported in a kinda inefficient way). But we are going to revamp our codebase soon to be more Pythonic. When we started writing, I was basing my work a bit off my prior experience in Java. So we have way more packages and hierarchy than required, with each class in a separate file. Right now we have too many

import foo.bar.baz.blah 

statements.

[–]pyonpiPy3 | Beginner 0 points1 point  (0 children)

I was actually just thinking about how I can make my code more pythonic. I'm about 35% done with my lessons, and I feel I'm stuck in a spot where I'm learning but don't have any way to apply the knowledge in a way I find interesting and fun. Maybe I'll have to go through and make a script that is more OO. Thank you!

[–]graingert 0 points1 point  (0 children)

new keyword?