551 - 600 Flashcards

1
Q

SQL.CASE

A

expression to add the conditional logic to a query. The SQLite CASE expression evaluates a list of conditions and returns an expression based on the result of the evaluation.

The CASE expression is similar to the IF-THEN-ELSE statement in other programming languages.

CASE case_expression
     WHEN when_expression_1 THEN result_1
     WHEN when_expression_2 THEN result_2
     ...
     [ ELSE result_else ] 
END
SELECT customerid, firstname, lastname,
       CASE country 
           WHEN 'USA' 
               THEN 'Domestic' 
           ELSE 'Foreign' 
       END CustomerGroup
FROM 
    customers
ORDER BY 
    LastName,
    FirstName;
CASE
     WHEN bool_expression_1 THEN result_1
     WHEN bool_expression_2 THEN result_2
     [ ELSE result_else ] 
END
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

MySQL.RLIKE

A

is used to performs a pattern match of a string expression against a pattern.

SELECT * FROM Employee   
WHERE Last_name RLIKE '^S' ;
SELECT * FROM Employee   
WHERE First_name RLIKE 'i$' ;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

MySQL.LENGTH()

A

is used to find the string length which is of type bytes.

SELECT LENGTH(item) FROM package099;
SELECT LENGTH(float_val) FROM float061;
SELECT LENGTH(mrp+sp) FROM package72;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

SQL.datetime

A

function to manipulate datetime values. The function accepts a time string and one or more modifiers.

SELECT datetime('now','-1 day','localtime'); 
SELECT datetime('now','localtime');
CREATE TABLE referrals(
    id INTEGER PRIMARY KEY,
    source TEXT NOT NULL,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

SQL.TIME()

A

function extracts the time part from a given time/datetime. Note: This function returns “00:00:00” if expression is not a datetime/time, or NULL if
expression is NULL.

SELECT *, (julianday(ShippedDate) - julianday(OrderDate)) as delivery_time
FROM Orders
ORDER BY delivery_time
SELECT TIME("19:30:10");
SELECT TIME("2017-08-15 19:30:10");
SELECT TIME("2017-08-15 19:30:10.000001");
SELECT TIME(NULL);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

sqlite3.cursor()

A

It is an object that is used to make the connection for executing SQL queries. It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database.

import sqlite3
connect = sqlite3.connect(":memory:")
connect = con.cursor()
connect.connection == connect
# True
def char_generator():
    for c in string.ascii_lowercase:
        yield (c,)

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from characters")
print(cur.fetchall())
con.close()
con = sqlite3.connect(":memory:")
cur = con.cursor()

sql = "create table people (name_last, age)"
cur.execute(sql)
who = "Yeltsin"
age = 72

стиль qmark:
sql = "insert into people values (?, ?)"
cur.execute(sql, (who, age))

именованный стиль:
sql = "select * from people where name_last=:who and age=:age"
cur.execute(sql, {"who": who, "age": age})

print(cur.fetchone())
con.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

sqlite3.fetchall() and sqlite3.fetchmany() and sqlite3.fetchone()

A

возвращаются одна или несколько строк.

sqlite3.fetchmany([size=cursor.arraysize]) — можно указывать, какое количество строк возвращается. По умолчанию параметр size равен значению cursor.arraysiz

conn = sqlite3.connect('movies.sqlite').cursor()
conn.execute("""SELECT COUNT(id) FROM directors""").fetchall()
connection = sqlite3.connect('sw_inventory.db')
cursor = connection.cursor()
cursor.execute('select * from switch')
sqlite3.Cursor at 0x104eda810>
cursor.fetchone()
Out[20]: ('0000.AAAA.CCCC', 'sw1', 'Cisco 3750', 'London, Green Str')
con = sqlite3.connect(":memory:")
con.execute("""
    select * from pragma_compile_options
    where compile_options like 'THREADSAFE=%'
""").fetchall()
cursor.execute('select * from switch')
from pprint import pprint

while True:
    three_rows = cursor.fetchmany(3)
    if three_rows:
    pprint(three_rows)
         else:
             break
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

sqlite3.Row

A

пытается имитировать кортеж в большинстве своих функций. Поддерживает доступ к результату запроса как к словарю, где ключ это имя столбца. Так же поддерживает обращение к столбцу по индексу, итерацию по строкам запроса, проверку на равенство и встроенную функцию len() для подсчета количества строк запроса. Если два объекта подряд имеют одинаковые столбцы, а их элементы равны, то эти объекты считаются равными.

conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('select * from stocks')

r = cursor.fetchone()

type(r)
👉 <class 'sqlite3.Row'>

tuple(r)
👉 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)

len(r)
👉 5

r[2]
👉 'RHAT'

r.keys()
👉 ['date', 'trans', 'symbol', 'qty', 'price']

r['qty']
👉 100.0

>>> for member in r:
...     print(member)

👉 2006-01-05
👉 BUY
👉 RHAT
👉 100.0
👉 35.14
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

sqlite3.cursor.keys

A

возвращает список имен столбцов. Сразу после запроса, это первый элемент каждого кортежа в Cursor.description.

conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('select * from stocks')

r = cursor.fetchone()

type(r)
👉 <class 'sqlite3.Row'>

tuple(r)
👉 ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)

len(r)
👉 5

r[2]
👉 'RHAT'

r.keys()
👉 ['date', 'trans', 'symbol', 'qty', 'price']

r['qty']
👉 100.0

>>> for member in r:
...     print(member)

👉 2006-01-05
👉 BUY
👉 RHAT
👉 100.0
👉 35.14
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

A

открывает соединение с файлом базы данных SQLite database. По умолчанию возвращает объект Connection, если не указана пользовательская фабрика. Если базы по пути нет, то будет созданна база в указоном пути с указаным именем.

  • database - путь к файлу с базой данных,
  • timeout - тайм-аут блокировки базы при изменении,
  • detect_types - обнаружения типов,
  • isolation_level - уровень изоляции,
  • check_same_thread - использование нескольких потоков,
  • factory - пользовательский класс Connection,
  • cached_statements - кэширование инструкций,
  • uri - интерпретировать подключение как URI.
  • sqlite3.connect(“:memory:”) - что бы использовать в памяти(будет уничтожена сразу после закрытия программы
import sqlite3
con = sqlite3.connect('example.db')
cur = con.cursor()
con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

sqlite3.row_factory()

A

change this attribute to a callable that accepts the cursor and the original row as a tuple and will return the real result row. This way, you can implement more advanced ways of returning results, such as returning an object that can also access columns by name.

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])

con.close()
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
    assert row[0] == row["name"]
    assert row["name"] == row["nAmE"]
    assert row[1] == row["age"]
    assert row[1] == row["AgE"]

con.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

SQL.WHERE

A

clause is used to filter records. It is used to extract only those records that fulfill a specified condition.

SELECT column1, column2, ...
FROM table_name
WHERE condition;
SELECT * FROM Customers
WHERE Country='Mexico';
SELECT * FROM Customers
WHERE CustomerID=1;
SELECT directors.name, COUNT(*) movie_count
FROM movies
JOIN directors ON movies.director_id = directors.id
WHERE movies.genres = ?
GROUP BY directors.name
ORDER BY movie_count DESC, directors.name
LIMIT 5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

SQL.LIKE

A

command is used in a WHERE clause to search for a specified pattern in a column.

You can use two wildcards with LIKE:

% - Represents zero, one, or multiple characters
_ - Represents a single character (MS Access uses a question mark (?) instead)

UPPER(title) LIKE '% LOVE''%'
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3 characters in length:

SELECT * FROM Customers
WHERE CustomerName LIKE 'a\_\_%';
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

sqlite3.execute(sql, parameters=(), /)

A

Execute an SQL statement. Values may be bound to the statement using placeholders.

conn = sqlite3.connect('movies.sqlite').cursor()
conn.execute("""SELECT COUNT(id) FROM directors""").fetchall()
keyword = "Love"

query = """
    SELECT * FROM tracks
    JOIN albums on albums.id = tracks.id
    WHERE tracks.name Like ?
"""
c.execute(query, (f"%{keyword}%", )) # <- Will replace "?" in the query with %keyword%
rows = c.fetchall()
cur = con.cursor()
# Create table
cur.execute('''CREATE TABLE stocks
               (date text, trans text, symbol text, qty real, price real)''')

Insert a row of data
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

Save (commit) the changes
con.commit()

We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
con.close()
def md5sum(t):
    return hashlib.md5(t).hexdigest()

con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", (b"foo",))
print(cur.fetchone()[0])

con.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

sqlite3.commit()

A

Commit any pending transaction to the database. If there is no open transaction, this method is a no-op.

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute('''create table stocks (date text, trans text, symbol text, qty real, price real)''')
cur.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")
con.commit()
cur.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

sqlite3.close()

A

Close the database connection. Any pending transaction is not committed implicitly; make sure to commit() before closing to avoid losing pending changes.

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])

con.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

sqlite3.executemany()

A

prepares a database operation (query or command) and executes it against all parameter sequences or mappings found in the sequence.

def collate_reverse(string1, string2):
    if string1 == string2:
        return 0
    elif string1 < string2:
        return 1
    else:
        return -1

con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)

cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
    print(row)
con.close()
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table lang (name, first_appeared)")

This is the qmark style:
cur.execute("insert into lang values (?, ?)", ("C", 1972))

The qmark style used with executemany():
lang_list = [("Fortran", 1957),
    ("Python", 1991),
    ("Go", 2009),
]
cur.executemany("insert into lang values (?, ?)", lang_list)

And this is the named style:
cur.execute("select * from lang where first_appeared=:year", {"year": 1972})
print(cur.fetchall())

con.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

SQL.UPPER

A

function converts a string to upper-case.

SELECT UPPER('SQL Tutorial is FUN!');
SELECT UPPER(CustomerName) AS UppercaseCustomerName
FROM Customers;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

SQL.VALUES

A

command specifies the values of an INSERT INTO statement.

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

SQL.LOWER

A

function converts a string to lower-case.

SELECT LOWER('SQL Tutorial is FUN!');
SELECT LOWER(CustomerName) AS LowercaseCustomerName
FROM Customers;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

SQL.CONCAT()

A

function adds two or more expressions together.

SELECT CONCAT("SQL ", "Tutorial ", "is ", "fun!") AS ConcatenatedString;
SELECT CONCAT(Address, " ", PostalCode, " ", City) AS Address
FROM Customers;
21
Q

SQL.CURRENT_DATE()

A

function returns the current date.
Note: The date is returned as “YYYY-MM-DD” (string) or as YYYYMMDD (numeric).

SELECT CURRENT_DATE() + 1;
22
Q

SQL.SQRT()

A

function returns the square root of a number.

SELECT SQRT(64);
SELECT SQRT(13);
23
Q

SQL.DROP DATABASE

A

statement is used to drop an existing SQL database.

DROP DATABASE databasename;
DROP DATABASE testDB;
24
Q

SQL.JOIN

A

clause is used to combine rows from two or more tables, based on a related column between them.

25
Q

SQL.(INNER)JOIN

A

Returns records that have matching values in both tables.

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
26
Q

SQL.LEFT JOIN

A

Returns all records from the left table, and the matched records from the right table.

27
Q

SQL.RIGHT JOIN

A

Returns all records from the right table, and the matched records from the left table.

28
Q

SQL.FULL JOIN

A

Returns all records when there is a match in either left or right table.

29
Q

SQL.CROSS JOIN

A

keyword returns all records from both tables (table1 and table2).

SELECT column_name(s)
FROM table1
CROSS JOIN table2;
30
Q

SQL.FULL OUTER JOIN

A

command returns all rows when there is a match in either left table or right table.

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
31
Q

SQL.AS

A

command is used to rename a column or table with an alias.

SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID;
32
Q

SQL.AUTO INCREMENT

A

allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

ALTER TABLE Persons AUTO_INCREMENT=100;
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen');
CREATE TABLE Persons (
    Personid int IDENTITY(1,1) PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);
CREATE TABLE Persons (
    Personid int NOT NULL AUTO_INCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (Personid)
);
33
Q

SQL.SET

A

command is used with UPDATE to specify which columns and values that should be updated in a table.

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
34
Q

SQL.Data Types

A

column defines what value the column can hold: integer, character, money, date and time, binary, and so on.

35
Q

SQL.LEN()

A

function returns the length of a string.

SELECT LEN('W3Schools.com');
SELECT LEN('2017-08');
36
Q

SQL.DATALENGTH()

A

function returns the number of bytes used to represent an expression.

SELECT DATALENGTH('W3Schools.com');
13
SELECT DATALENGTH('2017-08');
37
Q

SQL.SELECT

A

statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

SELECT CustomerName,City 
FROM Customers;
SELECT * FROM Customers;
38
Q

SQL.ALTER COLUMN

A

command is used to change the data type of a column in a table.

The following SQL changes the data type of the column named "BirthDate" in the "Employees" table to type year:

ALTER TABLE Employees
ALTER COLUMN BirthDate year;
39
Q

SQL.FROM

A

command is used to specify which table to select or delete data from.

The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table:

SELECT CustomerName,City FROM Customers;
The following SQL statement selects all the columns from the "Customers" table:

SELECT * FROM Customers;
40
Q

SQL.DROP COLUMN

A

command is used to delete a column in an existing table.

The following SQL deletes the "ContactName" column from the "Customers" table:

ALTER TABLE Customers
DROP COLUMN ContactName;
41
Q

SQL.SHOW COLUMNS

A

get a list of columns in a table

SHOW COLUMNS FROM table_name;
42
Q

SQL.ORDER BY

A

keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Отсортировать по последним 3м буквам
ORDER BY RIGHT(name, 3) ASC;
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT * FROM Customers
ORDER BY Country;
SELECT * FROM Customers
ORDER BY Country DESC;
SELECT * FROM Customers
ORDER BY Country, CustomerName;
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
43
Q

pandas.Index.get_level_values(level)

A

Return an Index of values for requested level.

This is primarily useful to get an individual level of values from a MultiIndex, but is provided on Index as well for compatibility.

idx = pd.Index(list('abc'))

print(idx)
👉 Index(['a', 'b', 'c'], dtype='object')

print(idx.get_level_values(0))
👉 Index(['a', 'b', 'c'], dtype='object')
# Create the MultiIndex object
midx = pd.MultiIndex.from_arrays((['AB', 'BC', 'CD', 'DE'], ['EF', 'FG', 'GH', 'HI']))

print(midx)
👉 MultiIndex([('AB', 'EF'),
               ('BC', 'FG'),
               ('CD', 'GH'),
               ('DE', 'HI')],)

print(midx.get_level_values(0))
👉 Index(['AB', 'BC', 'CD', 'DE'], dtype='object')

print(midx.get_level_values(1))
👉 Index(['EF', 'FG', 'GH', 'HI'], dtype='object')
44
Q

pandas.MultiIndex(levels=None, codes=None, sortorder=None, names=None, dtype=None, copy=False, name=None, verify_integrity=True)

❗ .from_arrays
❗ .from_tuples
❗ .from_product
❗ .from_frame

A

allows you to select more than one row and column in your index. It is a multi-level or hierarchical object for pandas object.

arrays = ['Sohom','Suresh','kumkum','subrata']
age= [10, 11, 12, 13]
marks=[90,92,23,64]

print(pd.MultiIndex.from_arrays([arrays,age,marks], names=('names', 'age','marks')))
MultiIndex([(  'Sohom', 10, 90),
            ( 'Suresh', 11, 92),
            ( 'kumkum', 12, 23),
            ('subrata', 13, 64)],
           names=['names', 'age', 'marks'])
df = {'name': ["Saikat", "Shrestha", "Sandi", "Abinash"],
               'Jobs': ["Software Developer", "System Engineer", "Footballer", "Singer"],
               'Annual Salary(L.P.A)': [12.4, 5.6, 9.3, 10]}
df = pd.DataFrame(df)

print(pd.MultiIndex.from_frame(df))
MultiIndex([(  'Saikat', 'Software Developer', 12.4),
            ('Shrestha',    'System Engineer',  5.6),
            (   'Sandi',         'Footballer',  9.3),
            ( 'Abinash',             'Singer', 10.0)],
           names=['name', 'Jobs', 'Annual Salary(L.P.A)'])
data = {
    'series': ['Peaky blinders', 'Sherlock', 'The crown', 'Queens Gambit', 'Friends'],
    'Ratings': [4.5, 5, 3.9, 4.2, 5],
    'Date': [2013, 2010, 2016, 2020, 1994]}

df = pd.DataFrame(data)
df.set_index(["series", "Ratings"], inplace=True, append=True, drop=False)

print(df.index)
MultiIndex([(0, 'Peaky blinders', 4.5),
            (1,       'Sherlock', 5.0),
            (2,      'The crown', 3.9),
            (3,  'Queens Gambit', 4.2),
            (4,        'Friends', 5.0)],
           names=[None, 'series', 'Ratings'])
45
Q

pandas.pivot_table((data, values=None, index=None, columns=None, aggfunc=’mean’, fill_value=None, margins=False, dropna=True, margins_name=’All’, observed=False, sort=True)

A

create a spreadsheet-style pivot table as a DataFrame. Levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.

df = pd.DataFrame({'A': ['John', 'Boby', 'Mina', 'Peter', 'Nicky'],
      'B': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'],
      'C': [27, 23, 21, 23, 24]})

table = pd.pivot_table(df, index =['A', 'B'])
print(table)
                 
A     B         C
Boby  Graduate  23
John  Masters   27
Mina  Graduate  21
Nicky Graduate  24
Peter Masters   23
table = pd.pivot_table(df, values ='A', index =['B', 'C'], columns =['B'], aggfunc = np.sum)
print(table)

B           Graduate Masters
B        C                  
Graduate 21     Mina     NaN
         23     Boby     NaN
         24    Nicky     NaN
Masters  23      NaN   Peter
         27      NaN    John
46
Q

slots

A

позволяют явно объявлять элементы данных (например, свойства) и запрещать создание словаря __dict__ и __weakref__. Во-первых, он ограничивает допустимый набор имен атрибутов объекта только перечисленными именами. Во-вторых, поскольку атрибуты теперь фиксированы, больше нет необходимости хранить атрибуты в словаре экземпляра, за счет такого ограничения можно повысить скорость работы при доступе к атрибутам и сэкономить место в памяти.

class Slot:
    \_\_slots\_\_ = ["a", "b"]

slot = Slot()
slot.a = 1
slot.a
👉 1

slot.a = 130
slot.a
👉 130

slot.b = 13
slot.b
👉 13

атрибут `c` не определен в списке `\_\_slots\_\_`
slot.c = 1
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'Slot' object has no attribute 'c'

slot.\_\_dict\_\_
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'Slot' object has no attribute '\_\_dict\_\_'
При использовании \_\_slots\_\_ происходит более быстрый доступ к атрибутам:

import timeit
class Foo(object): 
    \_\_slots\_\_ = 'foo'

class Bar(object):
     pass

slotted = Foo()
not_slotted = Bar()

def get_set_delete_fn(obj):
    def get_set_delete():
        obj.foo = 'foo'
        obj.foo
        del obj.foo
    return get_set_delete

измерим скорость доступа к атрибутам
min(timeit.repeat(get_set_delete_fn(slotted)))
👉 0.0844320549999793

min(timeit.repeat(get_set_delete_fn(not_slotted)))
👉 0.10562241299999187
47
Q

**@classmethod **

A

это обычный метод класса, имеющий доступ ко всем атрибутам класса, через который он был вызван. Следовательно, classmethod — это метод, который привязан к классу, а не к экземпляру класса. Короче можно вызывать прямо с класса без создания обьекта: Class.method()

@classmethod используется, когда вам нужно получить методы и атрибуты класса не относящиеся к какому-либо конкретному экземпляру, но тем не менее, каким-то образом привязанные к классу.
Что бы не передавать 100500 атрибутов и перенести конструирование обьекта в метод, как во втором примере.

class MyClass():
    TOTAL_OBJECTS = 0

    def \_\_init\_\_(self): 
        MyClass.TOTAL_OBJECTS = MyClass.TOTAL_OBJECTS + 1

    @classmethod
    def total_objects(cls): 
        print("Total objects: ", cls.TOTAL_OBJECTS)

Создаем объекты и каждый раз количество обьэктов увеличивается на 1!!!
# cls это ссылка на сам класс (не обьект!), питон передает его под капотом

my_obj1 = MyClass()
my_obj2 = MyClass()
my_obj3 = MyClass()

Вызываем classmethod
MyClass.total_objects()

👉 Total objects:  3
class BlueCat:
    bread = "Russian Blue"
    names = []
    count = 0

    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age
        BlueCat.increment_count()

    def meow(self):
        print(f"{self.name} of {self.bread} says: Meow!")

    @classmethod
    def increment_count(cls):
        cls.count += 1

    @classmethod
    def make_cat(cls, name):
        if name == "Tom":
            return cls("Tom", 2)
        elif name == "Angela":
            return cls("Angela", 1)
        return cls("Ginger", 1)

    @staticmethod
    def get_human_age(age):
        return age * 8


if \_\_name\_\_ == "\_\_main\_\_":
    tom = BlueCat.make_cat("Tom")
    angela = BlueCat.make_cat("Angela")
    tom.meow()
    angela.meow()
    print(BlueCat.count)
    print(angela.get_human_age(angela.age))

👉 Tom of Russian Blue says: Meow!
👉 Angela of Russian Blue says: Meow!
👉 2
👉 8
48
Q

@staticmethod

A

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

Это вроде обычной функции, определенной внутри класса и связанна с ним контекстом (внутри класса кот например, будет понятно, что считать будет возраст для котов), которая не имеет доступа к экземпляру, поэтому ее можно вызывать без создания экземпляра класса.

class Person():
    @staticmethod
    def is_adult(age):
        if age > 18:
            return True
        else:
            return False

Person.is_adult(23)
👉 True
class Person():
    @staticmethod
    def is_adult(age):
        if age > 18: 
            return True
        else: 
            return False

    @staticmethod
    def test():
        # не нужно писать self
        return "Test"

Вызываем без создания обьекта!!!
print(Person.is_adult(23))  
👉 True

print(Person.test())  
👉 Test
49
Q

set

A

is used to set some value in the class __dict__ object.
Позволяет определить поведение при присвоении значения дескриптору.

class Celsius:
    def \_\_get\_\_(self, instance, owner):
        return 5 * (instance.fahrenheit - 32) / 9

    def \_\_set\_\_(self, instance, value):
        instance.fahrenheit = 32 + 9 * value / 5

class Temperature:
    celsius = Celsius()

    def \_\_init\_\_(self, initial_f):
        self.fahrenheit = initial_f

t = Temperature(212)
print(t.celsius)
👉 100.0

t.celsius = 0
print(t.fahrenheit)
👉 32.0