[Road to Intermediate] Python seems to be all objects

Link to summary

https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8

Introduction

Apparently all Python is an object.

?? ?? ?? ?? ?? Really? ?? ?? ?? ??

What is an object?

A Python object is anything that Python handles. And the object has ** attributes **.

For example

class A:

    def __init__(self):
        self.x = 50

a = A()
print(a.x)

In the above code, the value is fetched using "period" like a.x. It is "** attribute **" (x) that can be retrieved using this period, and having an attribute also means ** object ** (a).

Take a look at an example of an object

class A:

    def __init__(self):
        self.x = 50


a = A()
print(type(a))
print(type(A))
print(type(30))
print(type(int))

'''
<class '__main__.A'>
<class 'type'>
<class 'int'>
<class 'type'>
'''

Looking at the above example, let's see that all Python data is actually an object.

The above code uses a built-in function called type. type is a function that returns the type of the object passed as an argument.

For example, the object a is of the type A of the main module. In addition, the class A, which is the original type, has a type called type. Similarly, the Python number 30, is of type int, and we know that 30 is an instance object of int.

As you can see, all Python data is apparently made up of objects.

--Class object --Instance object

It seems to be composed of.

Class object

So what is a class object?

As the name implies, a class object is Refers to the object of that class when you have finished defining the class.

For example

class A:
    x = 50
    print(10)

    def __init__(self):
        self.x = 100
        print(self.x)


print(A.x)
a = A()

Consider the above sources.

What will happen to the result of executing this?

this is

10
50
100

It looks like.

Python classes are executed as they are, except for def, and each line is executed like a normal statement.

So if you find class A when reading a Python file from above Go down as it is

And after loading class A, create a class object called A. Therefore, A becomes a ** class object ** when the reading is finished.

It is important that it is a class object.

Instance object

Instance objects are objects created from "class objects".

In particular

--30 (generated from int) --a (generated from A) --Function

And so on.

Because it is generated from a class object

class A:

    def __init__(self):
        self.x = 100


a = A()
print(type(a))
print(type(30))
print(type(int))

'''
<class '__main__.A'>
<class 'int'>
<class 'type'>
'''

a is a class object main. A that is a type of a 30 is a class object int of type 30

It has become.

In this way, instance objects are created from class objects.

Functions are also created from a class object called the function class.

application

Functions are objects as well. Objects can use attributes. Especially because the function is an instance object whose attributes can be set freely.

For example

--Check only once to see if matplotlib can be loaded

You can create a function called.

def can_load_matplotlib():
    if can_load_matplotlib.cache is None:
        try:
            import matplotlib
        except ImportError:
            can_load_matplotlib.cache = False
        else:
            can_load_matplotlib.cache = True
    return can_load_matplotlib.cache


can_load_matplotlib.cache = None

print(can_load_matplotlib())

Prepare the can_matplotlib function.

The Python file only creates the identity (memory) that "the function is on this line ~ ~" until the function is executed.

So, first of all, in the above code

--There is a function called can_load_matplotlib. --can_load_matplotlib is an instance object of Function class, and since attributes can be set freely from the outside, add cache attribute. --When you execute the function, it will try internally because it is None for the first time. --As a result, the call can be cached in a variable depending on whether it can be called successfully or not.

You can write the code.

I met this code when I copied the code of an overseas type of GitHub, and I thought it was amazing. But how much speed does caching increase? I don't know.

Finally

In Python, we've seen that classes, numbers, and strings are all objects.

I would like to write while distinguishing between an instance and a class object.

References

-How to check the variable type of Python -Type function to get / determine type in Python, isinstance function

Recommended Posts

[Road to Intermediate] Python seems to be all objects
A road to intermediate Python
[Road to Intermediate] Understanding Python Properties
[Road to intermediate Python] Use ternary operators
[Road to intermediate Python] Use lambda expressions
[Road to intermediate Python] Article link summary
[Python] There seems to be something called __dict__
[Road to Python Intermediate] Define __getattr__ function in class
[Road to intermediate Python] Define in in your own class
[Road to intermediate Python] Install packages in bulk with pip
[Road to intermediate Python] Use if statement in list comprehension
[Road to intermediate Python] Enables comparison operations with original classes
Road to Linux Intermediate: Network Edition
6 ways to string objects in Python
[Road to Python Intermediate] Call a class instance like a function with __call__
[Road to Python intermediate] Dynamically specify execution method by variable name
[Python] Road to snake charmer (1) Environment construction
The road to compiling to Python 3 with Thrift
I tried to implement what seems to be a Windows snipping tool in Python
Python has come to be recognized so far.
[Python] Road to a snake charmer (4) Tweak Numpy
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Python] Road to a snake charmer (6) Manipulate Pandas
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Road to Intermediate] What are Python's * args, ** kwargs?
Updated to Python 2.7.9
Starting with Python 3.10, the form returned by inspect.signature () seems to be based on typing.get_type_hints ().
"Backport" to python 2
[Python] Value Error: arrays must all be same length
Preparing to script control Rhino objects in Grasshopper / Python
[Python] tkinter Code that is likely to be reused
[Python] pandas Code that is likely to be reused
Only size-1 arrays can be converted to Python scalars
[Road to intermediate level] Utilize Python's built-in function vars
[Python] Road to a snake charmer (5) Play with Matplotlib
python> Is it possible to make in-line comments?> It seems that it has to be on multiple lines
What seems to be a template of the standard input part of the competition pro in python3