Table of Contents
Use type()
Use dir()
Home Backend Development Python Tutorial Python object-oriented obtaining object information

Python object-oriented obtaining object information

Apr 14, 2018 am 10:28 AM
python object Obtain

The content shared with you in this article is about obtaining object information in Python object-oriented. It has certain reference value. Friends in need can refer to it

When we get a reference to an object, How do you know what type this object is and what methods it has?

Use type()

First, we determine the object type, using the type() function:

Basic types can be judged using type():

>>> type(123)
<class &#39;int&#39;>
>>> type(&#39;jeff&#39;)
<class &#39;str&#39;>
>>> type(True)
<class &#39;bool&#39;>
>>> type(None)
<class &#39;NoneType&#39;>
Copy after login

If a variable points to a function or class, you can also use type() to determine:

>>> type(abs)
<class &#39;builtin_function_or_method&#39;>
Copy after login

But what type does the type() function return? It returns the corresponding Class type. If we want to judge in an if statement, we need to compare whether the type of the two variables is the same:

>>> type(123) == type(456)
True
>>> type(&#39;jeff&#39;) == type(&#39;1993&#39;)
True
>>> type(&#39;jeff&#39;) == str
True
>>> type(123) == int
True
>>> type(123) == type(&#39;jeff&#39;)
False
Copy after login

To judge the basic data type, you can directly write int, str, etc., but what if you want to judge whether an object is a function? manage? You can use the constants defined in the types module:

>>> import types
>>> def fn():
...     pass
...
>>> type(fn) == types.FunctionType
True
>>> type(abs) == types.BuiltinFunctionType
True
>>> type(lambda x:x) == types.LambdaType
True
>>> type((x for x in range(10))) == types.GeneratorType
True
Copy after login

Use isinstance()

For class inheritance relationships, it is very inconvenient to use type(). If we want to determine the type of class, we can use the isinstance() function.

Let’s review the last example. If the inheritance relationship is:

object, Animal, Dog, Husky

class Animal(object):
    def run(self):
        print(&#39;Animal is running...&#39;)

class Dog(Animal):
    def run(self):
        print(&#39;Dog is haha running...&#39;)

    def eat(self):
        print(&#39;Eating meat...&#39;)
class Cat(Animal):
    def run(self):
        print(&#39;Cat is miaomiao running...&#39;)

    def eat(self):
        print(&#39;Eating fish...&#39;)
class Husky(Dog):
    def run(self):
        print(&#39;Husky is miaomiao running...&#39;)
dog = Dog()
dog.run()
dog.eat()
xinxin = Husky()
xinxin.run()
cat = Cat()
cat.run()
cat.eat()
Copy after login
Dog is haha running...
Eating meat...
Husky is miaomiao running...
Cat is miaomiao running...
Eating fish...
Copy after login

Then, isinstance() can tell us whether an object is a certain type. First create 3 types of objects:

a= Animal()
d = Dog()
h = Husky()
print(isinstance(h,Husky))
print(isinstance(h,Dog))
print(isinstance(h,Animal))
print(isinstance(h,object))
print(isinstance(&#39;a&#39;,str))
print(isinstance(123,int))
Copy after login
True
True
True
True
True
True
Copy after login
print(isinstance(d,Husky))
False
Copy after login

and you can also determine whether a variable is one of certain types. For example, the following code can determine whether it is a list or a tuple:

>>> isinstance([1,2,3],(tuple,list))
True
>>> isinstance((1,2,3),(tuple,list))
True
>>> isinstance(1,(tuple,list))
False
Copy after login

Use dir()

If you want to get all the properties and methods of an object, you can use the dir() function, which returns a list containing strings, for example, getting a str object All attributes and methods:

>>> dir(123)
[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__pmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floorp__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rpmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloorp__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruep__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truep__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]
>>> dir(&#39;jeff&#39;)
[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;capitalize&#39;, &#39;casefold&#39;, &#39;center&#39;, &#39;count&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;, &#39;find&#39;, &#39;format&#39;, &#39;format_map&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isdecimal&#39;, &#39;isdigit&#39;, &#39;isidentifier&#39;, &#39;islower&#39;, &#39;isnumeric&#39;, &#39;isprintable&#39;, &#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;, &#39;maketrans&#39;, &#39;partition&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;, &#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;, &#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]
Copy after login
>>> dir(&#39;abc&#39;)  File "<stdin>", line 1
    dir(&#39;abc&#39;)
       ^
SyntaxError: invalid character in identifier注意括号要英文下的括号
Copy after login

Attributes and methods similar to __xxx__ have special uses in Python, such as the __len__ method returning the length. In Python, if you call the len() function to try to get the length of an object, in fact, inside the len() function, it automatically calls the __len__() method of the object, so the following code is equivalent :

>>> len(&#39;asd&#39;)
3
>>> &#39;asd&#39;.__len__()
3
Copy after login

The rest are ordinary attributes or methods, such as lower() returns a lowercase string:

>>> &#39;ASDD&#39;.lower()
&#39;asdd&#39;
Copy after login

It is not enough to just list the attributes and methods, cooperate with getattr() , setattr() and hasattr(), we can directly manipulate the state of an object:

>>> class MyObject(object):
...     def __init__(self):
...         self.x = 9
...     def power(self):
...         return self.x*self.x
>>>
>>> obj = MyObject()
>>> hasattr(obj,&#39;x&#39;)
True
>>> obj.x
9
>>> hasattr(obj,&#39;y&#39;)
False
>>> setattr(obj,&#39;y&#39;,19)
>>> hasattr(obj,&#39;y&#39;)
True
>>> getattr(obj,&#39;y&#39;)
19
Copy after login

If you try to obtain a non-existent attribute, an AttributeError will be thrown:

>>> getattr(obj,&#39;Z&#39;)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: &#39;MyObject&#39; object has no attribute &#39;Z&#39;
>>>
Copy after login

You can pass in a default parameter. If the attribute does not exist, it will return to the default value:

>>> getattr(obj,&#39;Z&#39;,404)
404
Copy after login

You can also get the method of the object:

>>> hasattr(obj, &#39;power&#39;) # 有属性&#39;power&#39;吗?
True
>>> getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn = getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;并赋值到变量 fn
>>> fn # fn 指向 obj.power
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn() # 调用 fn()与调用 obj.power()是一样的
81
Copy after login

Related recommendations:

Python object-oriented inheritance and polymorphism

Python object-oriented access restrictions

Python object-oriented classes and instances













##

The above is the detailed content of Python object-oriented obtaining object information. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles