python获取对象属性:dir()函数 、obj.__dict__ 、obj.inspect.getmebers

本文详细介绍了Python中获取对象属性的三种方式:__dict__属性、dir()函数以及inspect.getmembers。__dict__是对象属性的字典,dir()列出对象的所有属性,inspect.getmembers则提供更全面的成员信息,包括方法和属性。

一、Python __dict__与dir()

Python下一切皆对象,每个对象都有多个属性(attribute),Python对属性有一套统一的管理方案。

__dict__与dir()的区别:

  1. dir()是一个函数,返回的是list;
  2. __dict__是一个字典,键为属性名,值为属性值;__dict__包含了模块里可用的属性名-属性的字典;也就是可以使用模块名.属性名访问的对象。
  3. dir()用来寻找一个对象的所有属性,包括__dict__中的属性,__dict__是dir()的子集;

并不是所有对象都拥有__dict__属性。许多内建类型就没有__dict__属性,如list、dict、init,此时就需要dir() 来列出对象的所有属性。

二、__dict__属性

__dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值。

#!/usr/bin/python
# -*- coding: utf-8 -*-
class A(object):
    class_var = 1
    def __init__(self):
        self.name = 'xy'
        self.age = 2

    @property
    def num(self):
        return self.age + 10

    def fun(self):pass
    def static_f():pass
    def class_f(cls):pass

if __name__ == '__main__':#主程序
    a = A()
    print a.__dict__   
    # {'age': 2, 'name': 'xy'}   实例中的__dict__属性
    
    print A.__dict__   
    
    '''
    类A的__dict__属性
    {
    '__dict__': <attribute '__dict__' of 'A' objects>, 
    '__module__': '__main__',               #所处模块
    'num': <property object>,               #特性对象 
    'class_f': <function class_f>,          #类方法
    'static_f': <function static_f>,        #静态方法
    'class_var': 1, 'fun': <function fun >, #类变量
    '__weakref__': <attribute '__weakref__' of 'A' objects>, 
    '__doc__': None,                        #class说明字符串
    '__init__': <function __init__ at 0x0000000003451AC8>}
    '''

    a.level1 = 3
    a.fun = lambda :x
    print a.__dict__  
    #{'level1': 3, 'age': 2, 'name': 'xy','fun': <function <lambda> at 0x>}
    
    print A.__dict__  #与上述结果相同  上个 print A.__dict__ 

    A.level2 = 4
    print a.__dict__  #{'level1': 3, 'age': 2, 'name': 'xy'}
    print A.__dict__  #增加了level2属性

    print object.__dict__
    '''
	{'__setattr__': <slot wrapper '__setattr__' of 'object' objects>, '__reduce_ex__': <method '__reduce_ex__' of 'object' objects>,
	 '__new__': <built-in method __new__ of type object at 0x3d6358b8a0>, '__reduce__': <method '__reduce__' of 'object' objects>, 
	 '__str__': <slot wrapper '__str__' of 'object' objects>, '__format__': <method '__format__' of 'object' objects>, 
	 '__getattribute__': <slot wrapper '__getattribute__' of 'object' objects>, '__class__': <attribute '__class__' of 'object' objects>,
	  '__delattr__': <slot wrapper '__delattr__' of 'object' objects>, '__subclasshook__': <method '__subclasshook__' of 'object' objects>,
	   '__repr__': <slot wrapper '__repr__' of 'object' objects>, '__hash__': <slot wrapper '__hash__' of 'object' objects>,
	    '__sizeof__': <method '__sizeof__' of 'object' objects>, '__doc__': 'The most base type', '__init__': <slot wrapper '__init__' of 'object' objects>}
    '''

A.dict 中没有a.__dict__的一些属性,如age ,因为__dict__属性是该对象可访问的。age是A访问不到的,必须实例化才能用实例对象访问。
同样的class_f属性这个是a访问不到的,所以a.__dict__没有这个值。

简单说:
  1) 内置的数据类型没有__dict__属性

2) 每个类有自己的__dict__属性,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__

3) 对象也有自己的__dict__属性, 存储self.xxx 信息,父子类对象公用__dict__

三、dir()函数


1、dir()作用在实例上时,显示实例变量还有在实例变量所在类及所有它的基类中定义的方法和属性
2、dir()作用在类上时,显示类及所有它的基类中__dict__的内容,不包括元类
3、dir()作用在模块上时,显示模块的__dict__的内容
4、dir()不带参数时显示调用者的局部变量,等价于locals(),但返回的不是字典

​dir()是Python提供的一个API函数,dir()函数会自动寻找一个对象的所有属性(包括从父类中继承的属性)。

​ 一个实例的__dict__属性仅仅是那个实例的实例属性的集合,并不包含该实例的所有有效属性。所以如果想获取一个对象所有有效属性,应使用dir()。

print dir(A)
'''
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'class_f', 'class_var', 'fun', 'level1', 'level2', 'name', 'num', 'static_f']
'''
a_dict = a.__dict__.keys()
A_dict = A.__dict__.keys()
object_dict = object.__dict__.keys()
print a_dict  
print A_dict  
print object_dict 
'''
['fun', 'level1', 'age', 'name']

['__module__', 'level2', 'num', 'static_f', '__dict__', '__weakref__', '__init__', 'class_f', 'class_var', 'fun', '__doc__']

['__setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__format__', '__getattribute__', '__class__', '__delattr__', '__subclasshook__', '__repr__', '__hash__', '__sizeof__', '__doc__', '__init__']
'''

#因为每个类都有一个__doc__属性,所以需要去重,去重后然后比较
# dir()作用在实例上,显示实例变量a、还有在实例变量所在类A、及所有它的基类中定义的方法和属性
print set(dir(a)) == set(a_dict + A_dict + object_dict)  #True

四、inspect.getmebers

Inspect.getmembers(object [, predicate])
返回的内容比对象的__dict__包含的内容多,源码是通过dir()实现的。
这个方法是dir()的扩展版,它会将dir()找到的名字对应的属性一并返回,形如[(name, value), …]。
返回object的所有成员。
通常, 通过查找对象的__dict__属性来得到这些成员, 但是该函数可能返回存储在其他地方的object属性。例如, __doc__中的文档字符串, __name__中的对象名等。返回的成员都是一个(name, value)对列表。predicate是一个可选函数, 它将一个成员对象作为参数, 并返回True或False。只有predicate返回True时成员才被返回。像isfunction()和isclass()这样的函数可以用作判断函数。

getmembers(object[, predicate])

返回一个包含对象的所有成员的(name, value)列表。返回的内容比对象的__dict__包含的内容多,源码是通过dir()实现的。

predicate是一个可选的函数参数,被此函数判断为True的成员才被返回。

getmodule(object)

返回定义对象的模块

getsource(object)

返回对象的源代码

getsourcelines(object)

返回一个元组,元组第一项为对象源代码行的列表,第二项是第一行源代码的行号

ismodule,isclass,ismethod,isfunction,isbuiltin

一系列判断对象类型的方法,大都是包装了isinstance(object, types.FunctionType)之类语句的函数。

现在可以用类型判断来返回一个类的方法了:

class Foo(object):
‘’‘Foo doc’’’
def init(self, name):
self.__name = name

def getname(self):
    return self.__name

inspect.getmembers(Foo, inspect.ismethod)

https://www.cnblogs.com/zjchao/p/7894477.html

# Copyright (c) Microsoft Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Union from playwright._impl._errors import Error from playwright._impl._map import Map API_ATTR = "_pw_api_instance_" IMPL_ATTR = "_pw_impl_instance_" class ImplWrapper: def __init__(self, impl_obj: Any) -> None: self._impl_obj = impl_obj def __repr__(self) -> str: return self._impl_obj.__repr__() class ImplToApiMapping: def __init__(self) -> None: self._mapping: Dict[type, type] = {} def register(self, impl_class: type, api_class: type) -> None: self._mapping[impl_class] = api_class def from_maybe_impl( self, obj: Any, visited: Optional[Map[Any, Union[List, Dict]]] = None ) -> Any: # Python does share default arguments between calls, so we need to # create a new map if it is not provided. if not visited: visited = Map() if not obj: return obj if isinstance(obj, dict): if obj in visited: return visited[obj] o: Dict = {} visited[obj] = o for name, value in obj.items(): o[name] = self.from_maybe_impl(value, visited) return o if isinstance(obj, list): if obj in visited: return visited[obj] a: List = [] visited[obj] = a for item in obj: a.append(self.from_maybe_impl(item, visited)) return a api_class = self._mapping.get(type(obj)) if api_class: api_instance = getattr(obj, API_ATTR, None) if not api_instance: api_instance = api_class(obj) setattr(obj, API_ATTR, api_instance) return api_instance else: return obj def from_impl(self, obj: Any) -> Any: assert obj result = self.from_maybe_impl(obj) assert result return result def from_impl_nullable(self, obj: Any = None) -> Optional[Any]: return self.from_impl(obj) if obj else None def from_impl_list(self, items: Sequence[Any]) -> List[Any]: return list(map(lambda a: self.from_impl(a), items)) def from_impl_dict(self, map: Dict[str, Any]) -> Dict[str, Any]: return {name: self.from_impl(value) for name, value in map.items()} def to_impl( self, obj: Any, visited: Optional[Map[Any, Union[List, Dict]]] = None ) -> Any: if visited is None: visited = Map() try: if not obj: return obj if isinstance(obj, dict): if obj in visited: return visited[obj] o: Dict = {} visited[obj] = o for name, value in obj.items(): o[name] = self.to_impl(value, visited) return o if isinstance(obj, list): if obj in visited: return visited[obj] a: List = [] visited[obj] = a for item in obj: a.append(self.to_impl(item, visited)) return a if isinstance(obj, ImplWrapper): return obj._impl_obj return obj except RecursionError: raise Error("Maximum argument depth exceeded") def wrap_handler(self, handler: Callable[..., Any]) -> Callable[..., None]: def wrapper_func(*args: Any) -> Any: arg_count = len(inspect.signature(handler).parameters) return handler( *list(map(lambda a: self.from_maybe_impl(a), args))[:arg_count] ) if inspect.ismethod(handler): wrapper = getattr(handler.__self__, IMPL_ATTR + handler.__name__, None) if not wrapper: wrapper = wrapper_func setattr( handler.__self__, IMPL_ATTR + handler.__name__, wrapper, ) return wrapper wrapper = getattr(handler, IMPL_ATTR, None) if not wrapper: wrapper = wrapper_func setattr(handler, IMPL_ATTR, wrapper) return wrapper 分析这段代码,让我能看懂
06-05
"""Support for dynamic COM client support. Introduction Dynamic COM client support is the ability to use a COM server without prior knowledge of the server. This can be used to talk to almost all COM servers, including much of MS Office. In general, you should not use this module directly - see below. Example >>> import win32com.client >>> xl = win32com.client.Dispatch("Excel.Application") # The line above invokes the functionality of this class. # xl is now an object we can use to talk to Excel. >>> xl.Visible = 1 # The Excel window becomes visible. """ import traceback from itertools import chain from types import MethodType import pythoncom # Needed as code we eval() references it. import win32com.client import winerror from pywintypes import IIDType from . import build debugging = 0 # General debugging debugging_attr = 0 # Debugging dynamic attribute lookups. LCID = 0x0 # These errors generally mean the property or method exists, # but can't be used in this context - eg, property instead of a method, etc. # Used to determine if we have a real error or not. ERRORS_BAD_CONTEXT = [ winerror.DISP_E_MEMBERNOTFOUND, winerror.DISP_E_BADPARAMCOUNT, winerror.DISP_E_PARAMNOTOPTIONAL, winerror.DISP_E_TYPEMISMATCH, winerror.E_INVALIDARG, ] ALL_INVOKE_TYPES = [ pythoncom.INVOKE_PROPERTYGET, pythoncom.INVOKE_PROPERTYPUT, pythoncom.INVOKE_PROPERTYPUTREF, pythoncom.INVOKE_FUNC, ] def debug_print(*args): if debugging: for arg in args: print(arg, end=" ") print() def debug_attr_print(*args): if debugging_attr: for arg in args: print(arg, end=" ") print() # get the type objects for IDispatch and IUnknown PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch] PyIUnknownType = pythoncom.TypeIIDs[pythoncom.IID_IUnknown] _GoodDispatchTypes = (str, IIDType) def _GetGoodDispatch(IDispatch, clsctx=pythoncom.CLSCTX_SERVER): # quick return for most common case if isinstance(IDispatch, PyIDispatchType): return IDispatch if isinstance(IDispatch, _GoodDispatchTypes): try: IDispatch = pythoncom.connect(IDispatch) except pythoncom.ole_error: IDispatch = pythoncom.CoCreateInstance( IDispatch, None, clsctx, pythoncom.IID_IDispatch ) else: # may already be a wrapped class. IDispatch = getattr(IDispatch, "_oleobj_", IDispatch) return IDispatch def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx): # Get a dispatch object, and a 'user name' (ie, the name as # displayed to the user in repr() etc. if userName is None: if isinstance(IDispatch, str): userName = IDispatch ## ??? else userName remains None ??? else: userName = str(userName) return (_GetGoodDispatch(IDispatch, clsctx), userName) def _GetDescInvokeType(entry, invoke_type): # determine the wFlags argument passed as input to IDispatch::Invoke # Only ever called by __getattr__ and __setattr__ from dynamic objects! # * `entry` is a MapEntry with whatever typeinfo we have about the property we are getting/setting. # * `invoke_type` is either INVOKE_PROPERTYGET | INVOKE_PROPERTYSET and really just # means "called by __getattr__" or "called by __setattr__" if not entry or not entry.desc: return invoke_type if entry.desc.desckind == pythoncom.DESCKIND_VARDESC: return invoke_type # So it's a FUNCDESC - just use what it specifies. return entry.desc.invkind def Dispatch( IDispatch, userName=None, createClass=None, typeinfo=None, clsctx=pythoncom.CLSCTX_SERVER, ): IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx) if createClass is None: createClass = CDispatch lazydata = None try: if typeinfo is None: typeinfo = IDispatch.GetTypeInfo() if typeinfo is not None: try: # try for a typecomp typecomp = typeinfo.GetTypeComp() lazydata = typeinfo, typecomp except pythoncom.com_error: pass except pythoncom.com_error: typeinfo = None olerepr = MakeOleRepr(IDispatch, typeinfo, lazydata) return createClass(IDispatch, olerepr, userName, lazydata=lazydata) def MakeOleRepr(IDispatch, typeinfo, typecomp): olerepr = None if typeinfo is not None: try: attr = typeinfo.GetTypeAttr() # If the type info is a special DUAL interface, magically turn it into # a DISPATCH typeinfo. if ( attr[5] == pythoncom.TKIND_INTERFACE and attr[11] & pythoncom.TYPEFLAG_FDUAL ): # Get corresponding Disp interface; # -1 is a special value which does this for us. href = typeinfo.GetRefTypeOfImplType(-1) typeinfo = typeinfo.GetRefTypeInfo(href) attr = typeinfo.GetTypeAttr() if typecomp is None: olerepr = build.DispatchItem(typeinfo, attr, None, 0) else: olerepr = build.LazyDispatchItem(attr, None) except pythoncom.ole_error: pass if olerepr is None: olerepr = build.DispatchItem() return olerepr def DumbDispatch( IDispatch, userName=None, createClass=None, clsctx=pythoncom.CLSCTX_SERVER, ): "Dispatch with no type info" IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx) if createClass is None: createClass = CDispatch return createClass(IDispatch, build.DispatchItem(), userName) class CDispatch: def __init__(self, IDispatch, olerepr, userName=None, lazydata=None): if userName is None: userName = "<unknown>" self.__dict__["_oleobj_"] = IDispatch self.__dict__["_username_"] = userName self.__dict__["_olerepr_"] = olerepr self.__dict__["_mapCachedItems_"] = {} self.__dict__["_builtMethods_"] = {} self.__dict__["_enum_"] = None self.__dict__["_unicode_to_string_"] = None self.__dict__["_lazydata_"] = lazydata def __call__(self, *args): "Provide 'default dispatch' COM functionality - allow instance to be called" if self._olerepr_.defaultDispatchName: invkind, dispid = self._find_dispatch_type_( self._olerepr_.defaultDispatchName ) else: invkind, dispid = ( pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, pythoncom.DISPID_VALUE, ) if invkind is not None: allArgs = (dispid, LCID, invkind, 1) + args return self._get_good_object_( self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None ) raise TypeError("This dispatch object does not define a default method") def __bool__(self): return True # ie "if object:" should always be "true" - without this, __len__ is tried. # _Possibly_ want to defer to __len__ if available, but I'm not sure this is # desirable??? def __repr__(self): return "<COMObject %s>" % (self._username_) def __str__(self): # __str__ is used when the user does "print(object)", so we gracefully # fall back to the __repr__ if the object has no default method. try: return str(self.__call__()) except pythoncom.com_error as details: if details.hresult not in ERRORS_BAD_CONTEXT: raise return self.__repr__() def __dir__(self): attributes = chain(self.__dict__, dir(self.__class__), self._dir_ole_()) try: attributes = chain(attributes, [p.Name for p in self.Properties_]) except AttributeError: pass return list(set(attributes)) def _dir_ole_(self): items_dict = {} for iTI in range(0, self._oleobj_.GetTypeInfoCount()): typeInfo = self._oleobj_.GetTypeInfo(iTI) self._UpdateWithITypeInfo_(items_dict, typeInfo) return list(items_dict) def _UpdateWithITypeInfo_(self, items_dict, typeInfo): typeInfos = [typeInfo] # suppress IDispatch and IUnknown methods inspectedIIDs = {pythoncom.IID_IDispatch: None} while len(typeInfos) > 0: typeInfo = typeInfos.pop() typeAttr = typeInfo.GetTypeAttr() if typeAttr.iid not in inspectedIIDs: inspectedIIDs[typeAttr.iid] = None for iFun in range(0, typeAttr.cFuncs): funDesc = typeInfo.GetFuncDesc(iFun) funName = typeInfo.GetNames(funDesc.memid)[0] if funName not in items_dict: items_dict[funName] = None # Inspect the type info of all implemented types # E.g. IShellDispatch5 implements IShellDispatch4 which implements IShellDispatch3 ... for iImplType in range(0, typeAttr.cImplTypes): iRefType = typeInfo.GetRefTypeOfImplType(iImplType) refTypeInfo = typeInfo.GetRefTypeInfo(iRefType) typeInfos.append(refTypeInfo) # Delegate comparison to the oleobjs, as they know how to do identity. def __eq__(self, other): other = getattr(other, "_oleobj_", other) return self._oleobj_ == other def __ne__(self, other): other = getattr(other, "_oleobj_", other) return self._oleobj_ != other def __int__(self): return int(self.__call__()) def __len__(self): invkind, dispid = self._find_dispatch_type_("Count") if invkind: return self._oleobj_.Invoke(dispid, LCID, invkind, 1) raise TypeError("This dispatch object does not define a Count method") def _NewEnum(self): try: invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET enum = self._oleobj_.InvokeTypes( pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), () ) except pythoncom.com_error: return None # no enumerator for this object. from . import util return util.WrapEnum(enum, None) def __getitem__(self, index): # syver modified # Improved __getitem__ courtesy Syver Enstad # Must check _NewEnum before Item, to ensure b/w compat. if isinstance(index, int): if self.__dict__["_enum_"] is None: self.__dict__["_enum_"] = self._NewEnum() if self.__dict__["_enum_"] is not None: return self._get_good_object_(self._enum_.__getitem__(index)) # See if we have an "Item" method/property we can use (goes hand in hand with Count() above!) invkind, dispid = self._find_dispatch_type_("Item") if invkind is not None: return self._get_good_object_( self._oleobj_.Invoke(dispid, LCID, invkind, 1, index) ) raise TypeError("This object does not support enumeration") def __setitem__(self, index, *args): # XXX - todo - We should support calling Item() here too! # print("__setitem__ with", index, args) if self._olerepr_.defaultDispatchName: invkind, dispid = self._find_dispatch_type_( self._olerepr_.defaultDispatchName ) else: invkind, dispid = ( pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF, pythoncom.DISPID_VALUE, ) if invkind is not None: allArgs = (dispid, LCID, invkind, 0, index) + args return self._get_good_object_( self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None ) raise TypeError("This dispatch object does not define a default method") def _find_dispatch_type_(self, methodName): if methodName in self._olerepr_.mapFuncs: item = self._olerepr_.mapFuncs[methodName] return item.desc[4], item.dispid if methodName in self._olerepr_.propMapGet: item = self._olerepr_.propMapGet[methodName] return item.desc[4], item.dispid try: dispid = self._oleobj_.GetIDsOfNames(0, methodName) except: ### what error? return None, None return pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args): result = self._oleobj_.InvokeTypes( *(dispid, LCID, wFlags, retType, argTypes) + args ) return self._get_good_object_(result, user, resultCLSID) def _wrap_dispatch_( self, ob, userName=None, returnCLSID=None, ): # Given a dispatch object, wrap it in a class return Dispatch(ob, userName) def _get_good_single_object_(self, ob, userName=None, ReturnCLSID=None): if isinstance(ob, PyIDispatchType): # make a new instance of (probably this) class. return self._wrap_dispatch_(ob, userName, ReturnCLSID) if isinstance(ob, PyIUnknownType): try: ob = ob.QueryInterface(pythoncom.IID_IDispatch) except pythoncom.com_error: # It is an IUnknown, but not an IDispatch, so just let it through. return ob return self._wrap_dispatch_(ob, userName, ReturnCLSID) return ob def _get_good_object_(self, ob, userName=None, ReturnCLSID=None): """Given an object (usually the retval from a method), make it a good object to return. Basically checks if it is a COM object, and wraps it up. Also handles the fact that a retval may be a tuple of retvals""" if ob is None: # Quick exit! return None elif isinstance(ob, tuple): return tuple( map( lambda o, s=self, oun=userName, rc=ReturnCLSID: s._get_good_single_object_(o, oun, rc), ob, ) ) else: return self._get_good_single_object_(ob) def _make_method_(self, name): "Make a method object - Assumes in olerepr funcmap" methodName = build.MakePublicAttributeName(name) # translate keywords etc. methodCodeList = self._olerepr_.MakeFuncMethod( self._olerepr_.mapFuncs[name], methodName, 0 ) methodCode = "\n".join(methodCodeList) try: # print(f"Method code for {self._username_} is:\n", methodCode) # self._print_details_() codeObject = compile(methodCode, "<COMObject %s>" % self._username_, "exec") # Exec the code object tempNameSpace = {} # "Dispatch" in the exec'd code is win32com.client.Dispatch, not ours. globNameSpace = globals().copy() globNameSpace["Dispatch"] = win32com.client.Dispatch exec( codeObject, globNameSpace, tempNameSpace ) # self.__dict__, self.__dict__ name = methodName # Save the function in map. fn = self._builtMethods_[name] = tempNameSpace[name] return MethodType(fn, self) except: debug_print("Error building OLE definition for code ", methodCode) traceback.print_exc() return None def _Release_(self): """Cleanup object - like a close - to force cleanup when you don't want to rely on Python's reference counting.""" for childCont in self._mapCachedItems_.values(): childCont._Release_() self._mapCachedItems_ = {} if self._oleobj_: self._oleobj_.Release() self.__dict__["_oleobj_"] = None if self._olerepr_: self.__dict__["_olerepr_"] = None self._enum_ = None def _proc_(self, name, *args): """Call the named method as a procedure, rather than function. Mainly used by Word.Basic, which whinges about such things.""" try: item = self._olerepr_.mapFuncs[name] dispId = item.dispid return self._get_good_object_( self._oleobj_.Invoke(*(dispId, LCID, item.desc[4], 0) + (args)) ) except KeyError: raise AttributeError(name) def _print_details_(self): "Debug routine - dumps what it knows about an object." print("AxDispatch container", self._username_) try: print("Methods:") for method in self._olerepr_.mapFuncs: print("\t", method) print("Props:") for prop, entry in self._olerepr_.propMap.items(): print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}") print("Get Props:") for prop, entry in self._olerepr_.propMapGet.items(): print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}") print("Put Props:") for prop, entry in self._olerepr_.propMapPut.items(): print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}") except: traceback.print_exc() def __LazyMap__(self, attr): try: if self._LazyAddAttr_(attr): debug_attr_print( f"{self._username_}.__LazyMap__({attr}) added something" ) return 1 except AttributeError: return 0 # Using the typecomp, lazily create a new attribute definition. def _LazyAddAttr_(self, attr): if self._lazydata_ is None: return 0 res = 0 typeinfo, typecomp = self._lazydata_ olerepr = self._olerepr_ # We need to explicitly check each invoke type individually - simply # specifying '0' will bind to "any member", which may not be the one # we are actually after (ie, we may be after prop_get, but returned # the info for the prop_put.) for i in ALL_INVOKE_TYPES: try: x, t = typecomp.Bind(attr, i) # Support 'Get' and 'Set' properties - see # bug 1587023 if x == 0 and attr[:3] in ("Set", "Get"): x, t = typecomp.Bind(attr[3:], i) if x == pythoncom.DESCKIND_FUNCDESC: # it's a FUNCDESC r = olerepr._AddFunc_(typeinfo, t, 0) elif x == pythoncom.DESCKIND_VARDESC: # it's a VARDESC r = olerepr._AddVar_(typeinfo, t, 0) else: # not found or TYPEDESC/IMPLICITAPP r = None if not r is None: key, map = r[0], r[1] item = map[key] if map == olerepr.propMapPut: olerepr._propMapPutCheck_(key, item) elif map == olerepr.propMapGet: olerepr._propMapGetCheck_(key, item) res = 1 except: pass return res def _FlagAsMethod(self, *methodNames): """Flag these attribute names as being methods. Some objects do not correctly differentiate methods and properties, leading to problems when calling these methods. Specifically, trying to say: ob.SomeFunc() may yield an exception "None object is not callable" In this case, an attempt to fetch the *property* has worked and returned None, rather than indicating it is really a method. Calling: ob._FlagAsMethod("SomeFunc") should then allow this to work. """ for name in methodNames: details = build.MapEntry(self.__AttrToID__(name), (name,)) self._olerepr_.mapFuncs[name] = details def __AttrToID__(self, attr): debug_attr_print( "Calling GetIDsOfNames for property {} in Dispatch container {}".format( attr, self._username_ ) ) return self._oleobj_.GetIDsOfNames(0, attr) def __getattr__(self, attr): if attr == "__iter__": # We can't handle this as a normal method, as if the attribute # exists, then it must return an iterable object. try: invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET enum = self._oleobj_.InvokeTypes( pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), () ) except pythoncom.com_error: raise AttributeError("This object can not function as an iterator") # We must return a callable object. class Factory: def __init__(self, ob): self.ob = ob def __call__(self): import win32com.client.util return win32com.client.util.Iterator(self.ob) return Factory(enum) if attr.startswith("_") and attr.endswith("_"): # Fast-track. raise AttributeError(attr) # If a known method, create new instance and return. try: return MethodType(self._builtMethods_[attr], self) except KeyError: pass # XXX - Note that we current are case sensitive in the method. # debug_attr_print("GetAttr called for %s on DispatchContainer %s" % (attr,self._username_)) # First check if it is in the method map. Note that an actual method # must not yet exist, (otherwise we would not be here). This # means we create the actual method object - which also means # this code will never be asked for that method name again. if attr in self._olerepr_.mapFuncs: return self._make_method_(attr) # Delegate to property maps/cached items retEntry = None if self._olerepr_ and self._oleobj_: # first check general property map, then specific "put" map. retEntry = self._olerepr_.propMap.get(attr) if retEntry is None: retEntry = self._olerepr_.propMapGet.get(attr) # Not found so far - See what COM says. if retEntry is None: try: if self.__LazyMap__(attr): if attr in self._olerepr_.mapFuncs: return self._make_method_(attr) retEntry = self._olerepr_.propMap.get(attr) if retEntry is None: retEntry = self._olerepr_.propMapGet.get(attr) if retEntry is None: retEntry = build.MapEntry(self.__AttrToID__(attr), (attr,)) except pythoncom.ole_error: pass # No prop by that name - retEntry remains None. if retEntry is not None: # see if in my cache try: ret = self._mapCachedItems_[retEntry.dispid] debug_attr_print("Cached items has attribute!", ret) return ret except (KeyError, AttributeError): debug_attr_print("Attribute %s not in cache" % attr) # If we are still here, and have a retEntry, get the OLE item if retEntry is not None: invoke_type = _GetDescInvokeType(retEntry, pythoncom.INVOKE_PROPERTYGET) debug_attr_print( "Getting property Id 0x%x from OLE object" % retEntry.dispid ) try: ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1) except pythoncom.com_error as details: if details.hresult in ERRORS_BAD_CONTEXT: # May be a method. self._olerepr_.mapFuncs[attr] = retEntry return self._make_method_(attr) raise debug_attr_print("OLE returned ", ret) return self._get_good_object_(ret) # no where else to look. raise AttributeError(f"{self._username_}.{attr}") def __setattr__(self, attr, value): if ( attr in self.__dict__ ): # Fast-track - if already in our dict, just make the assignment. # XXX - should maybe check method map - if someone assigns to a method, # it could mean something special (not sure what, tho!) self.__dict__[attr] = value return # Allow property assignment. debug_attr_print( f"SetAttr called for {self._username_}.{attr}={value!r} on DispatchContainer" ) if self._olerepr_: # Check the "general" property map. if attr in self._olerepr_.propMap: entry = self._olerepr_.propMap[attr] invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT) self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) return # Check the specific "put" map. if attr in self._olerepr_.propMapPut: entry = self._olerepr_.propMapPut[attr] invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT) self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) return # Try the OLE Object if self._oleobj_: if self.__LazyMap__(attr): # Check the "general" property map. if attr in self._olerepr_.propMap: entry = self._olerepr_.propMap[attr] invoke_type = _GetDescInvokeType( entry, pythoncom.INVOKE_PROPERTYPUT ) self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) return # Check the specific "put" map. if attr in self._olerepr_.propMapPut: entry = self._olerepr_.propMapPut[attr] invoke_type = _GetDescInvokeType( entry, pythoncom.INVOKE_PROPERTYPUT ) self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) return try: entry = build.MapEntry(self.__AttrToID__(attr), (attr,)) except pythoncom.com_error: # No attribute of that name entry = None if entry is not None: try: invoke_type = _GetDescInvokeType( entry, pythoncom.INVOKE_PROPERTYPUT ) self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) self._olerepr_.propMap[attr] = entry debug_attr_print( "__setattr__ property {} (id=0x{:x}) in Dispatch container {}".format( attr, entry.dispid, self._username_ ) ) return except pythoncom.com_error: pass raise AttributeError(f"Property '{self._username_}.{attr}' can not be set.") 结合这个文件
09-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值