Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码


当前第2页 返回上一页


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class People:

  country='China'

  def __init__(self,name):

    self.name=name

  def people_info(self):

    print('%s is xxx' %(self.name))

obj=People('aaa')

setattr(People,'x',111) #等同于People.x=111

print(People.x)

#obj.age=18

setattr(obj,'age',18)

print(obj.__dict__)

#{'name': 'aaa', 'age': 18}

print(People.__dict__)

#{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1007d5620>, 'people_info': <function People.people_info at 0x10215d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'x': 111}


delattr()函数

描述:

delattr函数用于删除属性

delattr(x,'foobar)相当于del x.foobar

语法:

setattr(object,name)

参数:

object--对象

name--必须是对象的属性

返回值:

示例:


1

2

3

4

5

6

7

8

9

class People:

  country='China'

  def __init__(self,name):

    self.name=name

  def people_info(self):

    print('%s is xxx' %(self.name))

delattr(People,'country') #等同于del People.country

print(People.__dict__)

{'__module__': '__main__', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10073d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}


补充示例:


1

2

3

4

5

6

7

8

9

10

11

12

13

class Foo:

  def run(self):

    while True:

      cmd=input('cmd>>: ').strip()

      if hasattr(self,cmd):

        func=getattr(self,cmd)

        func()

  def download(self):

    print('download....')

  def upload(self):

    print('upload...')

# obj=Foo()

# obj.run()

相关推荐:

python3库numpy数组属性的查看方法

以上就是Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python编程如何判别线性

Python创建于英国吗

Python怎么安装运行

使用pip安装Python库的几种常用方法

如何在Python中使用json数据?(代码示例)

Python怎么把字符串变成字典

Python中的sample什么意思

Python 开发工具和框架安装实例步骤

Python如何安装pickle

Python验证码识别教程之灰度处理、二值化、降噪与tesserocr识别

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...