当查看目录中列出的属性和方法列表时,您如何知道哪些是属性,哪些是方法?
我正在努力学习用 Python 编程,并专注于更好地掌握如何使用 Standard 和其他模块。 dir 函数在解释器中似乎非常强大,但我想知道我是否因为缺乏 OOP 背景而遗漏了一些东西。 通过使用 S.Lotts 的书,我决定使用他的 Die 类来了解有关语法以及类和实例的使用的更多信息。
这是原始代码:
class Die(object):
''' simulate a six-sided die '''
def roll(self):
self.value=random.randrange(1,7)
return self.value
def getValue(self):
return self.value
我正在查看它,在创建一些实例后,我想知道单词值是否是一个关键字,以及类语句中单词对象的用途是什么,所以我决定通过更改类来找出答案定义如下:
class Die():
''' simulate a six-sided die '''
def roll(self):
self.ban=random.randrange(1,7)
return self.ban
def getValue(self):
return self.ban
该更改表明,我从实例中获得了相同的行为,但是当我执行 dir 时,实例中缺少以下方法/属性:
'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
_repr__', '__setattr__', '__str__', '__weakref__'
我还发现,当我在实例上执行 dir 时,我有一个我最终发现附加关键字-ban 是我的实例的一个属性。 这帮助我了解我可以使用 d1.ban 来访问我的实例的值。 我能弄清楚这是一个属性的唯一原因是我输入了 d1.happy 并得到了 AttributeError 我发现 d1.GetValue是附加到 Die 的方法,因为这是解释器告诉我的。
因此,当我尝试使用一些复杂但有用的模块(例如 BeautifulSoup)时,在输入 dir(instance) 后,我如何知道列出的哪些内容是我的实例的属性或实例的方法。 我需要知道这一点,因为这种探索告诉我,通过属性,我可以调用方法的结果,而通过方法,我可以在实例上调用函数。
这个问题可能太罗嗦了,但它确实帮助我更好地理解属性和方法之间的区别。 具体来说,当我查看在 Die 类的实例上调用 dir 的结果时,我看到了这个
['__doc__', '__module__', 'ban', 'getValue', 'roll']
因此,通过查看该列表来了解哪些是属性、哪些是方法,而无需诉诸尝试和错误或结果,这似乎很有用输入 hasattr(myInstance,suspectedAttributeName)。
在发布问题后,我尝试
for each in dir(d1):
print hasattr(d1,each)
严格地说,它告诉我所有方法都是属性。 但我无法在没有 () 的情况下调用方法,因此在我看来, hasattr() 具有误导性。
I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances.
Here is the original code:
class Die(object):
''' simulate a six-sided die '''
def roll(self):
self.value=random.randrange(1,7)
return self.value
def getValue(self):
return self.value
I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:
class Die():
''' simulate a six-sided die '''
def roll(self):
self.ban=random.randrange(1,7)
return self.ban
def getValue(self):
return self.ban
That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:
'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
_repr__', '__setattr__', '__str__', '__weakref__'
I also figured out that when I did a dir on an instance I had an additional keyword-ban which I finally figured out was an attribute of my instance. This helped me understand that I could use d1.ban to access the value of my instance. The only reason I could figure out that this was an attribute was I typed d1.happy and got an AttributeError I figured out that d1.GetValue was a method attached to Die because that is what the interpreter told me.
So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing dir(instance). I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.
This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this
['__doc__', '__module__', 'ban', 'getValue', 'roll']
So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in hasattr(myInstance,suspectedAttributeName).
After posting the question I tried
for each in dir(d1):
print hasattr(d1,each)
which tells me strictly speaking that all methods are attributes. but I can't call a method without the () so it seems to me that the hasattr() is misleading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不要使用“
print hasattr(d1,each)
”,而是尝试:“print every, type(getattr(d1,each))
”。 您应该会发现结果内容丰富。另外,尝试使用
help()
来代替dir()
,我认为您确实在寻找它。Instead of: "
print hasattr(d1,each)
", try: "print each, type(getattr(d1,each))
". You should find the results informative.Also, in place of
dir()
tryhelp()
, which I think you're really looking for.考虑使用标准库的
inspect
模块——它通常是最方便的内省方法,打包大量的功能(您可以从头开始实现它,但重用经过良好测试、精心设计的代码是一种好东西)。 请参阅 http://docs.python.org/library/inspect.html 了解所有内容详细信息,但例如inspect.getmembers(foo, inform.ismethod)
是获取 foo 的所有方法的绝佳方法(您将获得(name, value)
按名称排序的对)。Consider using the standard library's
inspect
module -- it's often the handiest approach to introspection, packaging up substantial chunks of functionality (you could implement that from scratch, but reusing well-tested, well-designed code is a good thing). See http://docs.python.org/library/inspect.html for all the details, but for exampleinspect.getmembers(foo, inspect.ismethod)
is an excellent way to get all methods of foo (you'll get(name, value)
pairs sorted by name).为什么会产生误导? 如果 obj.ban() 是一个方法,那么 obj.ban 就是相应的属性。 你可以有这样的代码:
或者
如果你想获取一个对象的方法列表,你可以尝试这个函数。 它并不完美,因为它也会触发不是方法的可调用属性,但对于 99% 的情况应该足够好:
Why is it misleading? If
obj.ban()
is a method, thenobj.ban
is the corresponding attribute. You can have code like this:or
If you want to get a list of methods on an object, you can try this function. It's not perfect, since it will also trigger for callable attributes that aren't methods, but for 99% of cases should be good enough:
这个受 Dive into Python 启发的
info
模块就达到了这个目的。This
info
module inspired from Dive into Python serves the purpose.有一个名为 callable 的内置方法。 您可以将其应用于任何对象,并且根据是否可以调用它,它将返回 True/False。 例如,
请注意 locals() 调用将返回一个包含当前范围中定义的所有内容的字典。 我这样做是因为字典中的项目只是字符串,我们需要在实际对象上运行可调用的。
There is a built in method called callable. You can apply it to any object and it will return True/False depending on if it can be called. e.g.
Note the locals() call will return a dictionary containing everything defined in your current scope. I did this because the items out of the dictionary are just strings, and we need to run callable on the actual object.
理想情况下,当使用像 BeautifulSoup 这样的复杂库时,您应该查阅其文档以了解每个类提供哪些方法。 但是,在极少数情况下,您没有易于访问的文档,您可以使用以下方法检查是否存在方法。
所有本身就是对象的方法都实现了 __call__ 方法,并且可以使用返回
True
的 callable() 方法进行检查(如果要检查的值具有) __call__
方法。下面的代码应该可以工作。
上面的代码将为所有方法返回 true,为所有不可调用属性(例如 ban 等数据成员)返回 false。 但是,此方法还会为任何可调用对象(如内部类)返回 True。 您还可以检查属性的类型是否为
instancemethod
Ideally, when using a complicated library like BeautifulSoup, you should consult its documentation to see what methods each class provides. However, in the rare case where you don't have easily accessible documentation, you can check for the presence of methods using the following.
All methods, which themselves are objects, implement the
__call__
method and can be checked using the callable() method which returnsTrue
, if the value being checked has the__call__
method.The following code should work.
The above code would return true for all the methods and false for all non callable attributes (such as data members like ban). However, this method also returns
True
for any callable objects (like inner classes). you can also check if the type of the attribute isinstancemethod