菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python hasattr() 函数

Python 内置函数 Python 内置函数


描述

hasattr() 函数用于判断对象是否包含对应的属性。

语法

hasattr 语法:

hasattr(object, name)

参数

  • object -- 对象。
  • name -- 字符串,属性名。

返回值

如果对象有该属性返回 True,否则返回 False。

实例

以下实例展示了 hasattr 的使用方法:

#!/usr/bin/python# -*- coding: UTF-8 -*-classCoordinate: x = 10y = -5z = 0point1 = Coordinate()print(hasattr(point1, 'x'))print(hasattr(point1, 'y'))print(hasattr(point1, 'z'))print(hasattr(point1, 'no'))# 没有该属性

输出结果:

True
True
True
False

Python 内置函数 Python 内置函数

AI 思考中...

1 篇笔记 写笔记

  1. #0

    yubi12137

    248***[email protected]

    41

    hasattr 可以在类内部使用,参数 1 为 self,可以查看对象自身的属性:

    class RepVGGBlock():
     def __init__(self, deploy=False):
     if deploy:
     self.rbr_reparam = 1
     def forward(self):
     if hasattr(self, 'rbr_reparam'):
     print(1)
     else:
     print(0)
    block1 = RepVGGBlock()
    block1.forward() # 0
    block2 = RepVGGBlock(deploy=True)
    block2.forward() # 1

    yubi12137

    248***[email protected]

    4年前 (2022年06月23日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /