Using getattr in Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • indiarocks
    New Member
    • Feb 2007
    • 20

    #1

    Using getattr in Python

    Just a basic question .... When using getattr for a specific method from a different class, can we somehow tell getattr to do a case-insensitive search.

    Say for eg. m = getattr(obj.__c lass__,'SetupCl ass') where obj is a object of a specific class.

    If SetupClass is declared as setUPClass or in any other way, the return value of m is going to be None, so can this be avoided in any way

    Thanks
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by indiarocks
    Just a basic question .... When using getattr for a specific method from a different class, can we somehow tell getattr to do a case-insensitive search.

    Say for eg. m = getattr(obj.__c lass__,'SetupCl ass') where obj is a object of a specific class.

    If SetupClass is declared as setUPClass or in any other way, the return value of m is going to be None, so can this be avoided in any way

    Thanks
    In your class, you can play with the names any way that you want to as I do here. In my default holder class "default" is appended inside the class so that I can pick out only that attrs that I want and stripped of on the way out. Have fun and keep posting,
    Barton

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Originally posted by indiarocks
      Just a basic question .... When using getattr for a specific method from a different class, can we somehow tell getattr to do a case-insensitive search.

      Say for eg. m = getattr(obj.__c lass__,'SetupCl ass') where obj is a object of a specific class.

      If SetupClass is declared as setUPClass or in any other way, the return value of m is going to be None, so can this be avoided in any way

      Thanks
      In this example 'name' is a class attribute of instance d2.__class__, but could have been a method as well:
      Code:
      >>> s = 'NaMe'
      >>> def lower_name(s, obj):
      ... 	for item in dir(obj):
      ... 		if item.lower() == s.lower():
      ... 			return item
      ... 		
      >>> lower_name(s, d2)
      'name'
      >>> getattr(d2.__class__, lower_name(s, d2))
      'Plane3D'
      >>> d2.name
      'Plane3D'
      >>>

      Comment

      Working...