Discuss / Python / 打卡

打卡

Topic source

感觉不需要getattr(a, 'x')这个函数啊,和a.x有啥区别

我不要你觉得 我只要我觉得 听我的!!!

Addictts

#3 Created at ... [Delete] [Delete and Lock User]

变量设置为私有是常见现象,那时你怎么通过a.x获得? 如果没有get()呢?

# 看下源码:

def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass

所以,没什么区别。

面向对象的思想类中定义的变量一般私有化处理,这样在类外面就无法用对象.属性名访问了,所以在类中需要定义获取属性的方法以用于外部访问

等等,私有了还能用getAttr这种嘛,不是要自己在class里写get set方法了?

zhr305

#7 Created at ... [Delete] [Delete and Lock User]

私有属性肯定会被改名啦,像__name,改为_Student_name

到时候如果getattr、hasattr,肯定会出错啦:

AttributeError: 'MyObject' object has no attribute


  • 1

Reply