简体   繁体   中英

Is there a way to writing staticmethods to python classes outside of the classes without extending the class?

I would like to this in the use case of which I can keep my DB schema (of which are declared via classes) in SQLAlchemy. At the same time, I would like to various staticmethods or util methods to these objects. But I would like to keep the schema clean and just be schema. Is there a way of writing these additional methods that would allow me to declare methods outside the scope of the class? Thanks.

Do you mean something like this ( lol() is a static "injected" method)?

class Foo (object):
    pass

Foo.lol = staticmethod (lambda: 1)
print Foo.lol ()

Your question is not entirely clear.

As staticmethods in Python are nothing else than simple functions bound to a class, you can easily do it like this:

def pseudoStaticMethod ():
    return 'It works.'

class A:
    def __init__ ( self ):
        print( 'A.__init__:', pseudoStaticMethod() )

class B:
    def __init__ ( self ):
        print( 'B.__init__:', pseudoStaticMethod() )

Or if you really want to assign them to the class/object:

def pseudoStaticMethod ():
    return 'It works.'

class A:
    myStaticMethod = staticmethod( pseudoStaticMethod )
    def __init__ ( self ):
        print( 'A.__init__:', self.myStaticMethod() )

class B:
    myStaticMethod = staticmethod( pseudoStaticMethod )
    def __init__ ( self ):
        print( 'B.__init__:', self.myStaticMethod() )

Or you can even make use of the fact that Python supports multiple inheritance:

class BaseClassWithAStaticMethod:
    @staticmethod
    def myStaticMethod ():
        return 'It works.'

class A ( BaseClassWithAStaticMethod ):
    def __init__ ( self ):
        print( 'A.__init__:', self.myStaticMethod() )

class B ( BaseClassWithAStaticMethod ):
    def __init__ ( self ):
        print( 'B.__init__:', self.myStaticMethod() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM