FrankyBoy
FrankyBoy

Reputation: 1946

Passing a class (not instance) in python?

Relatively new to python, coming from C#, so bear with me :)

Basically I got a ton of "nearly-duplicated" SQLAlchemy code that looks like so ...

def method1():    
    dbObj1 = Class1.query.filter_by(id=search_id).first()
    [a bunch of operations on this object]

....

def method2():
    dbObj2 = Class2.query.filter_by(id=search_id).first()
    [the same operations on this object]

The operations performed on these objects are the same and access properties that exist in both these classes. In C# or Java I'd solve that by having some sort of base class and/or using generics. However I have no clue how one would solve such duplication problems in Python.

Is there anything similar to generics? Or maybe that SQLAlchemy query could be changed in some way so these occurrences can be deduplicated?

Thanks for any inputs :)

EDIT: made the example a little more clear

Upvotes: 0

Views: 900

Answers (1)

Jina Jita
Jina Jita

Reputation: 136

You can actually just pass the class like this:

class A:
        def foo(self):
                return "foo"

class B: 
        def foo(self):
                return "bar"

def do_something(c):
        e = c()
        print(e.foo())


do_something(A)
do_something(B)

Upvotes: 1

Related Questions