Перейти к содержанию
Посмотреть в приложении

A better way to browse. Learn more.

Форум Академгородка, Новосибирск

A full-screen app on your home screen with push notifications, badges and more.

Чтобы установить это приложение на iOS и iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
Чтобы установить это приложение на Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Python

Опубликовано
Как отличить объект встроенного типа от сложного объекта(инстанцированного класса, например), от объекта-функции?

Изменено пользователем Гость

Рекомендуемые сообщения

Опубликовано

Смотри модуль inspect - #3.11.1 в доке от python 2.4.3

Там, например, описана функция isbuiltin и подобные...

 

А зачем это, если не секрет? ;-)

Опубликовано
  • Автор

QUOTE

isbuiltin( object)
Return true if the object is a built-in function.

А мне нужно работать с типами. Хочу визуализировать объект в виде дерева подобъектов.

 

def printObject(object, indent=0):
       retvalue=""
       indenter="  "
       indentString=""
       for i in range(0,indent):
               indentString=indentString+indenter
if str(type(object)).find('instance') <0 :
 retvalue+=indentString + "'"+str(object)+"'"
 return retvalue
if ( "__name__" in dir(object) and object.__name__ ) :
               retvalue+=indentString+"Name: " + str(object.__name__)+"\n"
       if ( "__class__" in dir(object) and object.__class__ ) :
               retvalue+=indentString+"Class: " + str(object.__class__)+"\n"
       if ( "__doc__" in dir(object) and object.__doc__ ) :
               retvalue+=indentString+"Desc: " + str(object.__doc__)+"\n"
       if (indent > 2): return "Depth limit"

       indentString=indentString+indenter

       for subObjectName in dir(object):
               if (subObjectName.startswith("__")): continue
               subObject=getattr(object, subObjectName)
               if str(type(subObject)).find('instance') >=0 :
                       retvalue+=indentString + subObjectName+":"+"\n"
                       retvalue+=printObject(getattr(object, subObjectName), indent+1)+"\n"
               else:
                       retvalue+=indentString + subObjectName+"="+"'"+str(subObject)+"'"+"\n"
       return retvalue 

Признак объекта пользовательского класса: str(type(subObject)).find('instance') >=0 https://academ.club/html/emoticons/blink.gif - у скриптовых языков своя специфика, но такая проверка мне претит. Есть другие способы? Или может быть сразу функция визуализации?

Изменено пользователем Гость

  • 2 недели спустя...
Опубликовано

Вместо

 for i in range(0,indent):
   indentString=indentString+indenter

лучше

 indentString = indenter * indent

Вместо name in dir(obj) лучше использовать hasattr(obj, name),

 

Ну и может сначала изучить модули repr (3.28) и pprint (3.27)

и понять чем они тебе не милы? ;-)

Изменено пользователем Гость

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

Гость
Ответить в этой теме...

Аккаунт

Навигация

Поиск

Поиск

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.