从属性访问 class 对象
Access a class object from its proprieties
我正在编写一个函数 A,它可以为您提供学校中的人的行为,我想对其进行排名,但我不能 link 函数 A 和 class“人”,我需要一种从 class 创建对象并根据函数 A 输出为其赋予专有“名称”的方法,然后通过相同的“名称”专有
访问该对象
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)
我还需要一种方法来检查对象是否存在其专有的“名称”
IIUC,您可以使用 vars()
:
在 python 中创建动态变量
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
或
def who_tried():
return 'Jack'
vars()[who_tried()] = person(who_tried())
Jack.credits_add(10)
print(Jack.credits)
>> 10
我正在编写一个函数 A,它可以为您提供学校中的人的行为,我想对其进行排名,但我不能 link 函数 A 和 class“人”,我需要一种从 class 创建对象并根据函数 A 输出为其赋予专有“名称”的方法,然后通过相同的“名称”专有
访问该对象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)
我还需要一种方法来检查对象是否存在其专有的“名称”
IIUC,您可以使用 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
或
def who_tried():
return 'Jack'
vars()[who_tried()] = person(who_tried())
Jack.credits_add(10)
print(Jack.credits)
>> 10