Home > front end >  getting field value from class instance in python
getting field value from class instance in python

Time:12-29

I don't understand how to get the value of a field instance from python class. I added what I need this code to do in get_person method. The output should be 3 or None.

class Digit:
    def __init__(self, digit)
        self.digit = digit
    
    def get_person(self):
        # I want to get the value for the field 'Person' from digit, if 'Person' exists
        # else None
        
        
    
inst1 = Digit('Team=Hawkeye|Weapon=Bow|Person=3')
inst2 = Digit('Comics')

print(inst1.get_person(),
      inst2.get_person())

CodePudding user response:

Your use case for the Digits class is possibly too broad given your two examples. Generally, it's best to have a class store the same types of data in each instance, for example Hawkeye, Bow, 3, and Thor, Hammer, 3. Adding Comics to inst2 suggests to me there is a better way of splitting up your classes, but without more context of what your code is actually doing it's hard to tell.

As was pointed out in the comments, using a string to store information like this is very messy and makes things hard to manage. A better way would be to use a dictionary, a way of storing names and values, for example, your team, weapon, and person values:

class Digit:
    def __init__(self, data):

        self.data = data
    
    def get_person(self):

        if "Person" in self.data.keys():
            return self.data["Person"]
        else:
            return None
    
inst1 = Digit({"Team":"Hawkeye", "Weapon":"Bow", "Person":3})
inst2 = Digit({"Comics":None})

print(inst1.get_person(),
      inst2.get_person())

A good starter guide for dictionaries can be found here

CodePudding user response:

Based on your example, there's no reason you shouldn't simply use dict:

inst1 = dict(Team='Hawkeye', Weapon='Bow', Person=3)
inst2 = dict()

print(inst1.get("Person"), inst2.get("Person"))  # prints '3 None'

CodePudding user response:

class Digit: # here you define your class
    def __init__(self, digit):
        self.digit = digit # you initialize (set) your attribute.
    def get_person(self):
        return self.digit # you return the attribute

If the object doesn't exist, you won't be able to call its member get_person anyway.

  • Related