是否有一种方法可以获取类实例上存在的属性列表?
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
期望的结果是输出"multi, str"。我希望它能看到脚本各个部分的当前属性。
是否有一种方法可以获取类实例上存在的属性列表?
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
期望的结果是输出"multi, str"。我希望它能看到脚本各个部分的当前属性。
当前回答
上面所有的答案都是正确的,你有三个选项可以选择
dir () vars () __dict__
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
>>> vars(a)
{'multi': 4, 'str': '2'}
>>> a.__dict__
{'multi': 4, 'str': '2'}
其他回答
上面所有的答案都是正确的,你有三个选项可以选择
dir () vars () __dict__
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
>>> vars(a)
{'multi': 4, 'str': '2'}
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> ', '.join(i for i in dir(a) if not i.startswith('__'))
'multi, str'
这当然会打印类定义中的任何方法或属性。你可以通过将i.startwith('__')更改为i.startwith('_')来排除“私有”方法。
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
您可能还会发现pprint有帮助。
你要这个干什么?如果不知道你的确切意图,可能很难得到最好的答案。
It is almost always better to do this manually if you want to display an instance of your class in a specific way. This will include exactly what you want and not include what you don't want, and the order will be predictable. If you are looking for a way to display the content of a class, manually format the attributes you care about and provide this as the __str__ or __repr__ method for your class. If you want to learn about what methods and such exist for an object to understand how it works, use help. help(a) will show you a formatted output about the object's class based on its docstrings. dir exists for programatically getting all the attributes of an object. (Accessing __dict__ does something I would group as the same but that I wouldn't use myself.) However, this may not include things you want and it may include things you do not want. It is unreliable and people think they want it a lot more often than they do. On a somewhat orthogonal note, there is very little support for Python 3 at the current time. If you are interested in writing real software you are going to want third-party stuff like numpy, lxml, Twisted, PIL, or any number of web frameworks that do not yet support Python 3 and do not have plans to any time too soon. The differences between 2.6 and the 3.x branch are small, but the difference in library support is huge.
请参见以下Python shell脚本执行顺序,它将给出从创建类到提取实例字段名的解决方案。
>>> class Details:
... def __init__(self,name,age):
... self.name=name
... self.age =age
... def show_details(self):
... if self.name:
... print "Name : ",self.name
... else:
... print "Name : ","_"
... if self.age:
... if self.age>0:
... print "Age : ",self.age
... else:
... print "Age can't be -ve"
... else:
... print "Age : ","_"
...
>>> my_details = Details("Rishikesh",24)
>>>
>>> print my_details
<__main__.Details instance at 0x10e2e77e8>
>>>
>>> print my_details.name
Rishikesh
>>> print my_details.age
24
>>>
>>> my_details.show_details()
Name : Rishikesh
Age : 24
>>>
>>> person1 = Details("",34)
>>> person1.name
''
>>> person1.age
34
>>> person1.show_details
<bound method Details.show_details of <__main__.Details instance at 0x10e2e7758>>
>>>
>>> person1.show_details()
Name : _
Age : 34
>>>
>>> person2 = Details("Rob Pike",0)
>>> person2.name
'Rob Pike'
>>>
>>> person2.age
0
>>>
>>> person2.show_details()
Name : Rob Pike
Age : _
>>>
>>> person3 = Details("Rob Pike",-45)
>>>
>>> person3.name
'Rob Pike'
>>>
>>> person3.age
-45
>>>
>>> person3.show_details()
Name : Rob Pike
Age can't be -ve
>>>
>>> person3.__dict__
{'age': -45, 'name': 'Rob Pike'}
>>>
>>> person3.__dict__.keys()
['age', 'name']
>>>
>>> person3.__dict__.values()
[-45, 'Rob Pike']
>>>