Python object-oriented obtaining object information
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 'int'> >>> type('jeff') <class 'str'> >>> type(True) <class 'bool'> >>> type(None) <class 'NoneType'>
If a variable points to a function or class, you can also use type() to determine:
>>> type(abs) <class 'builtin_function_or_method'>
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('jeff') == type('1993') True >>> type('jeff') == str True >>> type(123) == int True >>> type(123) == type('jeff') False
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
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('Animal is running...') class Dog(Animal): def run(self): print('Dog is haha running...') def eat(self): print('Eating meat...') class Cat(Animal): def run(self): print('Cat is miaomiao running...') def eat(self): print('Eating fish...') class Husky(Dog): def run(self): print('Husky is miaomiao running...') dog = Dog() dog.run() dog.eat() xinxin = Husky() xinxin.run() cat = Cat() cat.run() cat.eat()
Dog is haha running... Eating meat... Husky is miaomiao running... Cat is miaomiao running... Eating fish...
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('a',str)) print(isinstance(123,int))
True True True True True True
print(isinstance(d,Husky)) False
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
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) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__pmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floorp__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rpmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloorp__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruep__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truep__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> dir('jeff') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir('abc') File "<stdin>", line 1 dir('abc') ^ SyntaxError: invalid character in identifier注意括号要英文下的括号
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('asd') 3 >>> 'asd'.__len__() 3
The rest are ordinary attributes or methods, such as lower() returns a lowercase string:
>>> 'ASDD'.lower() 'asdd'
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,'x') True >>> obj.x 9 >>> hasattr(obj,'y') False >>> setattr(obj,'y',19) >>> hasattr(obj,'y') True >>> getattr(obj,'y') 19
If you try to obtain a non-existent attribute, an AttributeError will be thrown:
>>> getattr(obj,'Z') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'MyObject' object has no attribute 'Z' >>>
You can pass in a default parameter. If the attribute does not exist, it will return to the default value:
>>> getattr(obj,'Z',404) 404
You can also get the method of the object:
>>> hasattr(obj, 'power') # 有属性'power'吗? True >>> getattr(obj, 'power') # 获取属性'power' <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>> >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量 fn >>> fn # fn 指向 obj.power <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>> >>> fn() # 调用 fn()与调用 obj.power()是一样的 81
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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 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 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.

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.

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.

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.

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".
