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 setup是什么

Python通过什么来判断操作是否在分支结构中

Python int()怎么用

Python yield什么意思

学习Python可以做什么工作

Python如何解方程的三种方法

Python学习之观察者模式

Python是汇编语言吗

Python可以引用另一个文件的函数吗

Python编程有哪些ide

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




打赏

取消

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

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

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

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

评论

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