簡體   English   中英

isinstance(xxx,property)有效,但是在types模塊中對應什么?

[英]isinstance(xxx, property) works, but what does that correspond to in the types module?

我可以使用isinstance來測試一個屬性是否是一個屬性(實際上是在類上),但是在類型模塊中找不到與該屬性相對應的任何東西。

希望下面的代碼可以使這一點更加清楚。 我正在測試的所有其他內容都能很好地匹配。

class MyClass(object):
    def __init__(self):
        self._counter = 0

    def counter():

        doc = "The counter property."
        def fget(self):
            self._counter +=1
            return self._counter
        return locals()
    counter = property(**counter())

    def bar(self):
        self


foo = MyClass()
print "foo.counter", foo.counter
print "foo.counter", foo.counter


print "this will be an int. type(foo.counter):", type(foo.counter)


print "but the class knows it's  a property isinstance(foo.__class__.counter, property):", isinstance(foo.__class__.counter, property)


#let's see if we can determine the type of a given item...
import types

to_test = [3, foo.__class__.counter, foo.bar, {}]

print "matches against types:"
for k, v in vars(types).items():

    for test in to_test[:]:
        if type(test) == v:
            #flag a match, remove it from tests
            print ("  %s is a %s" % (test, v))
            to_test.remove(test)

#what's left over?  the property
print "\n\nno match found... :(", to_test

輸出...

foo.counter 1
foo.counter 2
this will be an int. type(foo.counter): <type 'int'>
but the class knows its  a property isinstance(foo.__class__.counter, property): True
matches against types:
  3 is a <type 'int'>
  <bound method MyClass.bar of <__main__.MyClass object at 0x106b06a50>> is a <type 'instancemethod'>
  {} is a <type 'dict'>


no match found... :( [<property object at 0x106afc838>]

是什么賦予了? 為什么在任何地方都無法根據類型識別屬性?

我很好奇的原因是我有一個調試功能,試圖漂亮地打印復雜的對象。 我很久以前就了解到,在這些對象上調用方法不是一個好主意。 因此,我傳入了一個默認的屬性類型列表,以供查看。

li_skiptype=[types.MethodType]

幾乎所有時間,我都會跳過方法,但是如果我從列表中刪除它們,我可以很好地打印它們。 添加它會很好 並讓我跳過屬性類型也是有條件的。

好吧...我只是很好奇為什么它們沒有類型。

types並不意味着是所有Python對象類型的全面集合。 模塊文檔中

此模塊為標准Python解釋器使用的某些對象類型定義名稱,但不為各種擴展模塊定義的類型定義名稱。

強調我的。

模塊中的大多數對象只是內置類型的別名,請參見模塊源代碼 這里的類型對象沒有什么神奇的東西; 它們只是更多的Python對象,而其中的一些對象不容易公開。 然后,該模塊只是一個方便。

您已經具有要測試的property對象,並且在types模塊中也不需要引用該對象。

在Python 3中, types模塊已進一步縮小為一組有限的類型,否則這些類型可能很難獲得引用。 已刪除的類型是可以直接以內置方式直接使用的類型。 再次引用Python 2文檔:

從Python 2.2開始,內置的工廠函數(例如int()str()也是相應類型的名稱。 現在,這是訪問類型的首選方法,而不是使用類型模塊。

由於property是從一開始就作為內置語言添加到語言中的,因此您無需直接以types公開該property

請注意,使用isinstance()幾乎總是更好,並允許使用子類。 如果必須限制測試只有一個類型,使用的is作為一個類型單身; 使用type(obj) is sometype而不是type(obj) == sometype 另請參閱Python樣式指南

對象類型比較應始終使用isinstance()而不是直接比較類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM