Home > Back-end >  Access a class object from its proprieties
Access a class object from its proprieties

Time:03-20

i was writing a function A that gives you person behavior in school and i wanted to rank it but i can't link the function A and the class "person" , i need a way to create an object from that class and give it a propriety "Name" based on the function A output and then access the object by the same "Name" propriety

class person:
    def __init__(self, name):
        self.name = name
        self.credits = 0

    def credits_add(self, amount):
        self.credits  = amount

def who_tried():
    #########
    ################
    #########################
    return name # Ex : "jack"

if who_tried():
    (who_tried()).credits_add(10)

and also i need a way to check if object exists by its propriety "Name"

CodePudding user response:

IIUC, you can make dynamic varibale in python using vars():

def who_tried():
    return 'Jack' # Ex : "jack"

vars()[who_tried()] = person(who_tried())
vars()[who_tried()].credits_add(30)
print(vars()[who_tried()].credits)

>> 30

or

def who_tried():
    return 'Jack' 

vars()[who_tried()] = person(who_tried())

Jack.credits_add(10)
print(Jack.credits)

>> 10
  • Related