如何(在运行时)检查一个类是否是另一个类的子类?

发布于 2024-10-16 02:57:59 字数 403 浏览 7 评论 0原文

假设我有一个花色类和四个花色子类:红心、黑桃、方块、梅花。

class Suit:
   ...
class Heart(Suit):
   ...
class Spade(Suit):
   ...
class Diamond(Suit):
   ...
class Club(Suit):
   ...

我有一个方法,它接收西装作为参数,它是一个类对象,而不是一个实例。更准确地说,它可能只接收四个值之一:Heart、Spade、Diamond、Club。我怎样才能做出确保这样的事情的断言?比如:

def my_method(suit):
   assert(suit subclass of Suit)
   ...

我正在使用 Python 3。

Let's say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club.

class Suit:
   ...
class Heart(Suit):
   ...
class Spade(Suit):
   ...
class Diamond(Suit):
   ...
class Club(Suit):
   ...

I have a method which receives a suit as a parameter, which is a class object, not an instance. More precisely, it may receive only one of the four values: Heart, Spade, Diamond, Club. How can I make an assertion which ensures such a thing? Something like:

def my_method(suit):
   assert(suit subclass of Suit)
   ...

I'm using Python 3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

若水微香 2024-10-23 02:57:59

您可以像 assert issubclass(suit, Suit) 一样使用 issubclass()

You can use issubclass() like this assert issubclass(suit, Suit).

谎言月老 2024-10-23 02:57:59

issubclass(class, classinfo)

摘录:

如果class是以下子类(直接、间接或虚拟),则返回 true
类信息

issubclass(class, classinfo)

Excerpt:

Return true if class is a subclass (direct, indirect or virtual) of
classinfo.

身边 2024-10-23 02:57:59

如果您有实例,则可以使用 isinstance;如果您有类,则可以使用 issubclass。通常认为这是一个坏主意。通常,在 Python 中,你可以通过尝试对某个对象执行某件事来确定该对象是否能够执行该操作。

You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.

场罚期间 2024-10-23 02:57:59

如果给定子类 sub 确实是超类 sup 的子类,则 issubclass(sub, sep) 布尔函数返回 true。

The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.

┼── 2024-10-23 02:57:59

issubclass 最小可运行示例

这是一个包含一些断言的更完整示例:

#!/usr/bin/env python3

class Base:
    pass

class Derived(Base):
    pass

base = Base()
derived = Derived()

# Basic usage.
assert issubclass(Derived, Base)
assert not issubclass(Base, Derived)

# True for same object.
assert issubclass(Base, Base)

# Cannot use object of class.
try:
    issubclass(derived, Base)
except TypeError:
    pass
else:
    assert False

# Do this instead.
assert isinstance(derived, Base)

GitHub 上游

在 Python 3.5.2 中测试。

issubclass minimal runnable example

Here is a more complete example with some assertions:

#!/usr/bin/env python3

class Base:
    pass

class Derived(Base):
    pass

base = Base()
derived = Derived()

# Basic usage.
assert issubclass(Derived, Base)
assert not issubclass(Base, Derived)

# True for same object.
assert issubclass(Base, Base)

# Cannot use object of class.
try:
    issubclass(derived, Base)
except TypeError:
    pass
else:
    assert False

# Do this instead.
assert isinstance(derived, Base)

GitHub upstream.

Tested in Python 3.5.2.

吹梦到西洲 2024-10-23 02:57:59

根据 Python doc,我们还可以使用 class.__mro__ 属性或 class.mro() 方法:

class Suit:
    pass
class Heart(Suit):
    pass
class Spade(Suit):
    pass
class Diamond(Suit):
    pass
class Club(Suit):
    pass

>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)

Suit in Heart.mro()  # True
object in Heart.__mro__  # True
Spade in Heart.mro()  # False

According to the Python doc, we can also use class.__mro__ attribute or class.mro() method:

class Suit:
    pass
class Heart(Suit):
    pass
class Spade(Suit):
    pass
class Diamond(Suit):
    pass
class Club(Suit):
    pass

>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)

Suit in Heart.mro()  # True
object in Heart.__mro__  # True
Spade in Heart.mro()  # False
ゝ偶尔ゞ 2024-10-23 02:57:59

@snakile,使用此代码:

#!/usr/bin/python3

class Suit: pass
class Heart(Suit): pass
class Spade(Suit): pass
class Diamond(Suit): pass
class Club(Suit): pass
class No(): pass

suit = Club()
f = issubclass(suit.__class__, Suit)
print(f)

suit = Spade()
f = issubclass(suit.__class__, Suit)
print(f)

suit = No()
f = issubclass(suit.__class__, Suit)
print(f)

输出:

$ /usr/bin/python3 sc.py
真的
真的
错误的

@snakile, use this code:

#!/usr/bin/python3

class Suit: pass
class Heart(Suit): pass
class Spade(Suit): pass
class Diamond(Suit): pass
class Club(Suit): pass
class No(): pass

suit = Club()
f = issubclass(suit.__class__, Suit)
print(f)

suit = Spade()
f = issubclass(suit.__class__, Suit)
print(f)

suit = No()
f = issubclass(suit.__class__, Suit)
print(f)

Output:

$ /usr/bin/python3 sc.py
True
True
False
叹梦 2024-10-23 02:57:59

您可以使用内置的 issubclass。但类型检查通常被认为是不必要的,因为您可以使用鸭子类型。

You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.

向日葵 2024-10-23 02:57:59

使用 issubclass 似乎是一种编写日志级别的干净方法。使用它感觉有点奇怪......但它看起来比其他选项更干净。

class Error(object): pass
class Warn(Error): pass
class Info(Warn): pass
class Debug(Info): pass

class Logger():
    LEVEL = Info

    @staticmethod
    def log(text,level):
        if issubclass(Logger.LEVEL,level):
            print(text)
    @staticmethod
    def debug(text):
        Logger.log(text,Debug)   
    @staticmethod
    def info(text):
        Logger.log(text,Info)
    @staticmethod
    def warn(text):
        Logger.log(text,Warn)
    @staticmethod
    def error(text):
        Logger.log(text,Error)

Using issubclass seemed like a clean way to write loglevels. It kinda feels odd using it... but it seems cleaner than other options.

class Error(object): pass
class Warn(Error): pass
class Info(Warn): pass
class Debug(Info): pass

class Logger():
    LEVEL = Info

    @staticmethod
    def log(text,level):
        if issubclass(Logger.LEVEL,level):
            print(text)
    @staticmethod
    def debug(text):
        Logger.log(text,Debug)   
    @staticmethod
    def info(text):
        Logger.log(text,Info)
    @staticmethod
    def warn(text):
        Logger.log(text,Warn)
    @staticmethod
    def error(text):
        Logger.log(text,Error)
失眠症患者 2024-10-23 02:57:59
#issubclass(child,parent)

class a:
    pass
class b(a):
    pass
class c(b):
    pass

print(issubclass(c,b))#it returns true
#issubclass(child,parent)

class a:
    pass
class b(a):
    pass
class c(b):
    pass

print(issubclass(c,b))#it returns true
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文