python对象的属性和方法

时间:2012-07-18 08:12:30

标签: python

在python中,所有数据都是对象,任何对象都应该具有属性和方法。 有人知道没有任何属性和方法的python对象吗?

>>> len(dir(1))
64

4 个答案:

答案 0 :(得分:2)

overriding __dir____getattribute__

很容易实现
class Empty(object):
    def __dir__(self):
        return []
    def __getattribute__(self, name):
        raise AttributeError("'{0}' object has no attribute '{1}'".format(type(self).__name__, name))

e = Empty()
dir(e)
[]
e.__name__
AttributeError: 'Empty' object has no attribute '__name__'

(在中,Empty需要是新式的类,因此class Empty(object):是必需的;在中,旧式的类已经灭绝所以{{ 1}}就足够了。)

答案 1 :(得分:1)

没有遇到任何这样的对象,它没有任何属性..见下文

In [74]: class dummy():
   ....:     pass
   ....:

In [75]: d1 = dummy()

In [76]: dir(d1)
Out[76]: ['__doc__', '__module__']

In [77]: len(dir(d1))
Out[77]: 2

即使没有属性......

In [78]: dir(None)
Out[78]:
['__class__',
 '__delattr__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']

答案 2 :(得分:1)

是的! (或没有...)

def AMeta(name, bases, dct):
    class NoProp:
        pass
    del NoProp.__doc__
    del NoProp.__module__
    return NoProp

class A:
    __metaclass__ = AMeta

print dir(A), 'len', len(dir(A))

print
print 'but... A.__name__ is', A.__name__
print 'Delete it!'
try:
    del A.__name__
except Exception as e:
    print 'Did not work: ', repr(e)

print
print 'and... A.__dict__ is', A.__dict__
print 'Delete it!'
try:
    del A.__dict__
except Exception as e:
    print 'Did not work: ', repr(e)

print
print 'and... A.__bases__ is', A.__bases__
print 'Delete it!'
try:
    del A.__bases__
except Exception as e:
    print 'Did not work: ', repr(e)

print 
print 'What is the type of A?'
t = type(A)
print t, 'which is a', type(t)

print "All of these will raise an AttributeError:"
print "A.__class__, A.__module__, (and maybe some others which are usually there too...)"

通常情况下,所有对象都具有某些属性。但是在使用元类时,您可以自定义创建类的方式,并且可以使用它。

但是,即使dir为空,您仍然可以访问A.__name__A.__dict__A.__bases__

这是我做的测试给了我的:

[] len 0

but... A.__name__ is NoProp
Delete it!
Did not work:  TypeError('__name__ must be a string object',)

and... A.__dict__ is {}
Delete it!
Did not work:  TypeError('__dict__ must be a dictionary object',)

and... A.__bases__ is ()
Delete it!
Did not work:  TypeError('__bases__ must be a tuple object',)

What is the type of A?
<type 'classobj'> which is a <type 'type'>
All of these will raise an AttributeError:
A.__class__, A.__module__, (and maybe some others which are usually there too...)

答案 3 :(得分:0)

您可以创建一个没有任何&#34; public&#34;属性和方法:

class Bare(object):
    pass

但是这个对象将有一些内部/标准方法和属性:

>>> x = Bare()
>>> dir(x)
['__class__',
 '__delattr__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']

Python没有强制私有方法和属性的概念,一切都暴露出来。但是,按照惯例,您应该避免外部访问以_开头的方法和属性,这些应保留供内部使用(Python内部方法的双下划线)。在实践中,您可以检查没有任何&#34; public&#34;属性:

>>> filter(lambda a: a[0] != '_', dir(x))
[]

>>> len(filter(lambda a: a[0] != '_', dir(x)))
0

即使您通过覆盖__dir____getattribute__作弊,内置属性仍然存在,可以使用父类中的__getattribute__进行访问(感谢martineau告诉我这个):

class FakeEmpty:
    def __dir__(self):
        return []
    def __getattribute__(self, name):
        raise AttributeError("'{0}' object has no attribute '{1}'".format(type(self).__name__, name))

>>> e = FakeEmpty()
>>> object.__getattribute__(e, '__class__')
__main__.Empty

所以答案是:不是真的,但你几乎可以伪造它。