我有一个像这样设置的课程
class Vehicle:
def __init__(self, seats, wheels, engine):
self.seats = seats
self.wheels = wheels
self.engine = engine
我得到了一个像这样的实例
porsche = Vehicle(2, 4, "gas")
我无法弄清楚如何使用实例“porsche”在屏幕上写出“__init__
”部分中每个自我初始化的名称。
所需的输出是这样的句子:
"I have a Vehicle. It has seats, wheels, and an engine."
座椅轮和发动机来自班级。
我检索了Vehicle并使用它将其放入字符串:
porsche.__class__.__name__
但是对于我的生活无法弄清楚如何获得每个self.
对象
答案 0 :(得分:1)
您的问题似乎是询问如何知道对象上的属性名称。对于简单对象(没有插槽),它足以检查__dict__
。所以从这样的事情开始:
def show(x):
return "I have a {}. It has {}".format(type(x).__name__, ", ".join(x.__dict__))
然后
>>> show(Vehicle(1, 1, 1))
'I have a Vehicle. It has seats, wheels, engine'
答案 1 :(得分:1)
您可以使用obj.__dict__
来访问实例fields / members / data attributes。
你在找这样的东西吗?
class Vehicle:
def __init__(self, seats, wheels, engine):
self.seats = seats
self.wheels = wheels
self.engine = engine
def description(self):
# 'Vehicle'
name = self.__class__.__name__
# ['seats', 'wheels', 'engine']
field_names = self.__dict__.keys()
return "I have a %s. It has these fields: %s" % (
name, ', '.join(field_names))
porsche = Vehicle(2, 4, "gas")
print(porsche.description())
输出:
I have a Vehicle. It has these fields: engine, wheels, seats
请注意,这些字段名称将以任意顺序排列(dicts在Python中是无序的),不一定按照__init__()
中定义的顺序排列。