Мой вклад демонстрирует разницу между методами @classmethod
, @staticmethod
и экземплярами, включая то, как экземпляр может косвенно вызвать @staticmethod
. Но вместо косвенного вызова @staticmethod
из экземпляра, делая его частным, может быть более «питоническим». Получение чего-то из частного метода здесь не показано, но в принципе это та же концепция.
#!python3
from os import system
system('cls')
# % % % % % % % % % % % % % % % % % % % %
class DemoClass(object):
# instance methods need a class instance and
# can access the instance through 'self'
def instance_method_1(self):
return 'called from inside the instance_method_1()'
def instance_method_2(self):
# an instance outside the class indirectly calls the static_method
return self.static_method() + ' via instance_method_2()'
# class methods don't need a class instance, they can't access the
# instance (self) but they have access to the class itself via 'cls'
@classmethod
def class_method(cls):
return 'called from inside the class_method()'
# static methods don't have access to 'cls' or 'self', they work like
# regular functions but belong to the class' namespace
@staticmethod
def static_method():
return 'called from inside the static_method()'
# % % % % % % % % % % % % % % % % % % % %
# works even if the class hasn't been instantiated
print(DemoClass.class_method() + '\n')
''' called from inside the class_method() '''
# works even if the class hasn't been instantiated
print(DemoClass.static_method() + '\n')
''' called from inside the static_method() '''
# % % % % % % % % % % % % % % % % % % % %
# >>>>> all methods types can be called on a class instance <<<<<
# instantiate the class
democlassObj = DemoClass()
# call instance_method_1()
print(democlassObj.instance_method_1() + '\n')
''' called from inside the instance_method_1() '''
# # indirectly call static_method through instance_method_2(), there's really no use
# for this since a @staticmethod can be called whether the class has been
# instantiated or not
print(democlassObj.instance_method_2() + '\n')
''' called from inside the static_method() via instance_method_2() '''
# call class_method()
print(democlassObj.class_method() + '\n')
''' called from inside the class_method() '''
# call static_method()
print(democlassObj.static_method())
''' called from inside the static_method() '''
"""
# whether the class is instantiated or not, this doesn't work
print(DemoClass.instance_method_1() + '\n')
'''
TypeError: TypeError: unbound method instancemethod() must be called with
DemoClass instance as first argument (got nothing instead)
'''
"""
Эти шаги могут использоваться для эмуляции этой функциональности:
1) Создать новую временную таблицу.
CREATE TEMPORARY TABLE temporary_table LIKE target_table;
2) При желании отбросить все индексы из временной таблицы в
SHOW INDEX FROM temporary_table;
DROP INDEX `PRIMARY` ON temporary_table;
DROP INDEX `some_other_index` ON temporary_table;
3) Загрузите CSV во временную таблицу
LOAD DATA INFILE 'your_file.csv'
INTO TABLE temporary_table
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(field1, field2);
4) Скопируйте данные, используя ON DUPLICATE KEY UPDATE
SHOW COLUMNS FROM target_table;
INSERT INTO target_table
SELECT * FROM temporary_table
ON DUPLICATE KEY UPDATE field1 = VALUES(field1), field2 = VALUES(field2);
5) Удалить временную таблицу
DROP TEMPORARY TABLE temporary_table;
Используя SHOW INDEX FROM
и SHOW COLUMNS FROM
, этот процесс может быть автоматизирован для любой данной таблицы.
мы можем заменить первый (два шага) нижним одиночным запросом в процедуре, разделяемой (Jan).
1) и 2) мы можем создать новую таблицу с той же ссылочной структурой и без каких-либо индексов.
CREATE TEMPORARY TABLE tempor_table SELECT * FROM target_table WHERE 1 = 0;
Вместо ..
1) Создайте новую временную таблицу.
CREATE TEMPORARY TABLE tempor_table LIKE target_table;
2) При желании отбросьте все индексы из временной таблицы, чтобы ускорить работу.
ПОКАЗАТЬ ИНДЕКС ИЗ временного_таблицы; DROP INDEX PRIMARY
ВКЛ. Временная таблица; DROP INDEX some_other_index
ON временная таблица;