Duck typing and class methods (or, how to use a method from both a class and an instance?)

后端 未结 3 1325
后悔当初
后悔当初 2021-01-07 05:47

I have some code which I would like to pass instances or classes interchangeably. All I will do in that code is to call a method that I expect both classes and instances to

3条回答
  •  难免孤独
    2021-01-07 06:11

    How about something like:

    import inspect
    
    class A(object):
       @staticmethod
       def go(obj):
          if inspect.isclass(obj):
             print 'class'
          else:
             print 'instance'
    
    A.go(int) # class
    A.go(1)   # instance
    A.go(A)   # class
    A.go(A()) # instance
    

提交回复
热议问题