第四章——对象

4-7 dir(type)

  • output
>>> output
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro']
  • __abstractmethods__
    默认为空,是一个对支持的抽象基类的描述。
  • __base__
    记录了对象的基类
  • __bases__
    记录了多重继承的基类
  • __call__
    使实例能够像函数一样被调用
type.__call__(int) 等同于 type(int)
  • __class__
    返回一个所属类的一个引用
    a = A()b = a.__class__()是一样的
  • __dict__
    类的__dict__里存放了类的静态函数、类函数、普通函数、全局变量以及一些内置的属性
    对象的__dict__中存储了一些self.xxx的一些东西

Q:can i call the python function with their address
A:You cannot execute a function at a given address.


  • __dictoffset__

the dictoffset attribute tells you the offset to where you find the pointer to the dict object in any instance object that has one

  • __eq__
a, b = 1, 1
a.__eq__(b) == (a==b)
  • __format__
    类内重载__format__可以实现自定义的format输出
class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return 'x: %s, y: %s' % (self.x, self.y)

    def __format__(self, code):
        return 'x: {x}, y: {y}'.format(x = self.x, y = self.y)

p = point(3, 4)
print("Here is a point {p}".format(p))

>>> Here is a point x: 3, y: 4

__str__和__repr__同理

  • __lt__ __le__ __eq__ __ne__ __ge__ __gt__
    在 a 和 b 之间进行全比较。具体的,lt(a, b) 与 a < b 相同, le(a, b) 与 a <= b 相同,eq(a, b) 与 a == b 相同,ne(a, b) 与 a != b 相同,gt(a, b) 与 a > b 相同,ge(a, b)a >= b 相同。注意这些函数可以返回任何值,无论它是否可当作布尔值。关于全比较的更多信息请参考比较运算

  • __getattribute__
    __getattribute__是属性访问拦截器,就是当这个类的属性被访问时,会首先自动调用类的__getattribute__方法。所以可以自定义getattribute方法实现对类的自定义检测,或是输出log之类的。

class myclass():
    def __init__(self,name="name"):
        self.name = name
    def __getattribute__(self,*arg):
        print("Check arg {} First".format(repr(arg)))
        return object.__getattribute__(self,*arg)


a = myclass("test")
print(a.name)

Output:
Check arg ('name',) First
test
  • __mro__
    对于支持继承的编程语言来说,其方法(属性)可能定义在当前类,也可能来自于基类,所以在方法调用时就需要对当前类和基类进行搜索以确定方法所在的位置。而搜索的顺序就是所谓的「方法解析顺序」(Method Resolution Order,或MRO)

  • __subclasses__
    SSTI经常使用到的属性

  • __text_signature__
    与python的C-API有关

+__weakrefoffset__
undocumented
in short: nonzero weakrefoffset means given type support weak references

posted @ 2021-01-06 17:02  TaiiHu  阅读(51)  评论(0)    收藏  举报