Skip to main content
Active reading. Fixed the weird syntax highlighting (as a result, the diff looks more extensive than it really is - use view "Side-by-side markdown" to compare).
Source Link
Peter Mortensen
  • 31.4k
  • 22
  • 110
  • 134

NoI have no idea what's your actual use case is, but you can do something like this using a descriptor:

class Desc(object):
    
    def __get__(self, ins, typ):
        if ins is None:
            print 'Called by a class.'
            return lambda : typ.__name__
        else:
            print 'Called by an instance.'
            return lambda : ins.__class__.__name__
        
class X(object):
    id = Desc()

x = X()
print x.id()
print X.id()

Output:

Output

Called by an instance.
X
Called by a class.
X
Called by an instance.
X
Called by a class.
X

No idea what's your actual use case is, but you can do something like this using a descriptor:

class Desc(object):
    
    def __get__(self, ins, typ):
        if ins is None:
            print 'Called by a class.'
            return lambda : typ.__name__
        else:
            print 'Called by an instance.'
            return lambda : ins.__class__.__name__
        
class X(object):
    id = Desc()

x = X()
print x.id()
print X.id()

Output:

Called by an instance.
X
Called by a class.
X

I have no idea what's your actual use case is, but you can do something like this using a descriptor:

class Desc(object):

    def __get__(self, ins, typ):
        if ins is None:
            print 'Called by a class.'
            return lambda : typ.__name__
        else:
            print 'Called by an instance.'
            return lambda : ins.__class__.__name__

class X(object):
    id = Desc()

x = X()
print x.id()
print X.id()

Output

Called by an instance.
X
Called by a class.
X
Source Link
Ashwini Chaudhary
  • 252.1k
  • 60
  • 478
  • 519

No idea what's your actual use case is, but you can do something like this using a descriptor:

class Desc(object):
    
    def __get__(self, ins, typ):
        if ins is None:
            print 'Called by a class.'
            return lambda : typ.__name__
        else:
            print 'Called by an instance.'
            return lambda : ins.__class__.__name__
        
class X(object):
    id = Desc()

x = X()
print x.id()
print X.id()

Output:

Called by an instance.
X
Called by a class.
X