简体   繁体   English

Python-有没有一种方法可以获取对象的所有属性

[英]Python - is there a way to get all the attributes of an object

So I have a class called 'Car' in another .py file (MyClasses.py) 所以我在另一个.py文件(MyClasses.py)中有一个名为“汽车”的类

class Car:
    tires = 4
    color = ""
    speed = 0
    engine = ""

and in my main 而在我的主要

import MyClasses

ferrari = MyClasses.Car()
ferrari.color = "Red"
ferrari.engine = "Fast"
ferrari.speed = 200

for prpty in ferrari:
    print(prpty)

the output I want is like this: 我想要的输出是这样的:

tires = 4
color = Red
speed = 200
engine = Fast

I know the format of the output depends on me. 我知道输出的格式取决于我。 Only if in my for-loop I can get the property name and its value base on my object. 只有在我的for循环中,我才能获得基于对象的属性名称及其值。

dir() gives all attributes, in order to get class variables we filter it as shown below: dir()提供了所有属性,为了获取类变量,我们对其进行过滤,如下所示:

>>> dir(ferrari)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'color', 'engine', 'speed', 'tires']

>>> classVariables = [attr for attr in dir(ferrari) if not callable(getattr(ferrari, attr)) and not attr.startswith("__")]

>>> print(classVariables)
['color', 'engine', 'speed', 'tires']

Why not make a function to print all the attributes of your class ... This would save you all the hassle... Like: 为什么不制作一个函数来打印类的所有属性呢?这将节省您所有的麻烦……

class Car:
       tires=4
       speed=0
       color=" "
       def print_atr(self):
               print("tires = ",self.tires)
               print("speed = ",self.speed)
               print("color = ",self.color)

Here is a solution: 这是一个解决方案:

ferrari = Car()
errari.color = "Red"
ferrari.engine = "Fast"
ferrari.speed = 200
for attr in [i in dir(ferrari) if not i.startswith('_')]:
    print('{}: {}'.format(attr, getattr(ferrari, attr))

Better to define the __str__ at the time of creation of the class. 最好在创建类时定义__str__ If class is yours and you create the class then whey not include all the attribute there. 如果class是您的,并且您创建了class,那么乳清不要在其中包含所有属性。 If you just want to get the list all the attributes of a class then dir will be good. 如果您只想获取列表的类的所有属性,那么dir会很好。 But for your intended output 但是对于您预期的输出

class Car:
    tires = 4
    color = ""
    speed = 0
    engine = ""

    def __str__(self):
        return "tires="+str(self.tires)+"\ncolor="+self.color+"\nengine="+self.engine
        ##Include all the attribute here as above in intended way.


ferrari = Car()
ferrari.color = "Red"
ferrari.engine = "Fast"
ferrari.speed = 200

honda = Car()
honda.color = "Black"
honda.engine = "Slow"
honda.speed = 100

print ferrari
print honda

Like in JAVA we have toString() method that we can override to change the default behavior of printing an object, similarly we do have in Python too that we can define behavior of printing an object. 像在JAVA中一样,我们具有toString()方法,可以重写该方法以更改打印对象的默认行为,同样,在Python中,我们也可以定义打印对象的行为。

Your intended out put is 您打算投放的是

tires = 4
color = Red
speed = 200
engine = Fast

so update def __str__(self): method (little bit of update) and will work for everytime you print any object of the Car class 所以更新def __str__(self):方法(一点点更新),并且每次您打印Car类的任何object都可以使用

the simplest solution is using vars() for example: 最简单的解决方案是使用vars()例如:

print vars(ferrari)

will print 将打印

{'engine': 'Fast', '__module__': '__main__', 'color': 'Red', 'tires': 4, 'speed': 200, '__doc__': None}

to get what you want here is the code 得到你想要的是这里的代码

fe = vars(ferrari)
for item in [i for i in fe if not i.startswith("_")]:
    print('{}: {}'.format(item, getattr(ferrari, item)))

this will print 这将打印

engine: Fast
color: Red
tires: 4
speed: 200

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM