Python Forum
What would be a way to check if a variable or class existed in an if?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What would be a way to check if a variable or class existed in an if?
#8
You can do it with inspect:
class MyTestClass:
    def __init__(self):
        self.list1 = [ ]
        self.fptr = self.method_a
        self.mamals = {
            'rat': {'has_tail': True},
            'dog': {'has_tail': True},
            'guppy': {'has_tail': False, 'has_fin': True}
        }
        self.fptr()

    def method_a(self):
        pass

def try_me():
    import inspect
    from pprint import pprint

    mtc = MyTestClass()

    # Get everything
    for name, member in inspect.getmembers(mtc):
        if name.startswith('__'):
            continue
        pprint(f'name: {name}, member: {member}')

if __name__ == "__main__":
    try_me()
output:
Output:
('name: fptr, member: <bound method MyTestClass.method_a of '  '<__main__.MyTestClass object at 0x00000000028CBE10>>') 'name: list1, member: []' ("name: mamals, member: {'rat': {'has_tail': True}, 'dog': {'has_tail': True}, "  "'guppy': {'has_tail': False, 'has_fin': True}}") ('name: method_a, member: <bound method MyTestClass.method_a of '  '<__main__.MyTestClass object at 0x00000000028CBE10>>')
Reply


Messages In This Thread
RE: What would be a way to check if a variable or class existed in an if? - by Larz60+ - Dec-22-2017, 01:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable Types in a class nafshar 9 2,725 Oct-07-2022, 07:13 PM
Last Post: deanhystad
  can Inner Class reference the Outer Class's static variable? raykuan 6 6,287 Jul-01-2022, 06:34 AM
Last Post: SharonDutton
  Calling a base class variable from an inherited class CompleteNewb 3 1,888 Jan-20-2022, 04:50 AM
Last Post: CompleteNewb
  Can we access instance variable of parent class in child class using inheritance akdube 3 14,169 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Class variable / instance variable ifigazsi 9 4,583 Jul-28-2020, 11:40 AM
Last Post: buran
  Assignment of non-existing class variable is accepted - Why? DrZ 6 4,486 Jul-13-2020, 03:53 PM
Last Post: deanhystad
  Limiting valid values for a variable in a class WJSwan 5 3,905 Jul-06-2020, 07:17 AM
Last Post: Gribouillis
  check pandas variable type cools0607 3 7,002 Jun-12-2020, 09:28 AM
Last Post: buran
  Newbie: Help with variable selection in a class Slack86 5 2,855 Apr-07-2020, 08:41 PM
Last Post: jefsummers
  Using variable from a class in another .py script keegan_010 4 3,203 Mar-25-2020, 07:47 AM
Last Post: keegan_010

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020