我已经阅读了__getitem__Python文档中的大部分文档以及stackoverflow,因此这不是一个重复的问题.但我仍然无法理解它的含义.
所以我能理解的__getitem__是用于实现类似的调用self[key].但它的用途是什么?
假设我有一个以这种方式定义的python类:
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __getitem__(self,key):
print ("Inside `__getitem__` method!")
return getattr(self,key)
p = Person("Subhayan",32)
print (p["age"])
Run Code Online (Sandbox Code Playgroud)
这会按预期返回结果.但为什么要__getitem__首先使用?我也听说过__getitem__内部的Python调用.但它为什么这样做呢?
有人可以更详细地解释一下吗?
有人可以解释get-childitem命令中-include和-filter选项之间的区别.
下面是我试图执行的两段代码.它们都用于查找特定目录中的文本文件:
PS C:\Users\352997> get-childitem -path Desktop\Extras -filter *.txt
Directory: C:\Users\352997\Desktop\Extras
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 12/22/2014 4:05 PM 140 Expense_report.txt
-a--- 1/14/2015 4:41 PM 211 Extras.txt
-a--- 2/10/2015 2:46 PM 259 Learn Dutch.txt
PS C:\Users\352997> get-childitem -path Desktop\Extras -include *.txt
Run Code Online (Sandbox Code Playgroud)
- 上面的命令没有产生结果----
所以这或多或少是一个理论问题.我有一个核心机器,据说功能强大,但只有一个核心.现在我有两个选择:
多线程:就我的知识而言,即使我因为GIL而拥有它们,我也无法在我的机器中使用多个内核.因此,在这种情况下,它没有任何区别.
多处理:这是我怀疑的地方.我可以在单个核心机器上进行多处理吗?或者每次我必须检查我的机器中可用的核心,然后运行完全相同或更少数量的进程?
有人可以指导一下机器中多处理和核心之间的关系.
我知道这是一个理论问题,但我的概念对此并不十分清楚.
我正在尝试使用Python中的数据类,我想做的是在我的类中拥有一个计算字段,并将 sort_index 字段添加到调用中,但也希望将其冻结,以便我无法修改任何属性定义后的此类。下面是我的代码:
from dataclasses import dataclass, field
def _get_year_of_birth(age: int, current_year: int=2019):
return current_year - age
@dataclass(order=True, frozen=True)
class Person():
sort_index: int = field(init=False, repr=False)
name: str
lastname: str
age: int
birthyear: int = field(init=False)
def __post_init__(self):
self.sort_index = self.age
self.birthyear = _get_year_of_birth(self.age)
if __name__ == "__main__":
persons = [
Person(name="Jack", lastname="Ryan", age=35),
Person(name="Jason", lastname="Bourne", age=45),
Person(name="James", lastname="Bond", age=60)
]
sorted_persons = sorted(persons)
for person in sorted_persons:
print(f"{person.name} and {person.age} and year of birth is : {person.birthyear}")
Run Code Online (Sandbox Code Playgroud)
看来我无法在类中设置自定义排序字段,也无法创建从其他属性计算得出的任何属性,因为我使用的是 freeze …
有人可以指出此代码段出了什么问题。它没有给出任何结果。
import multiprocessing
results = []
def log_results(result):
results.append(result)
def multiply(x, y):
print(f"Gets here for process name {multiprocessing.current_process().name()}")
return x * y
if __name__ == "__main__":
pool = multiprocessing.Pool()
numbers = [(1,1), (2,2), (3,3)]
for x, y in numbers:
print (f"Checking x {x} and y {y}")
pool.apply_async(multiply, (x, y), callback=log_results)
pool.close()
pool.join()
print(results)
Run Code Online (Sandbox Code Playgroud)
结果是一个空列表,在这种情况下不应该对吗?我已经使用了apply_async和map_async。两者都没有给出正确的输出。有人可以帮我吗
我正在尝试mypyPython 中的一些基本迭代,并编写了以下代码库:
from typing import Iterator
from datetime import date, timedelta
class DateIterator:
def __init__(self, start_date, end_date):
self.start_date = start_date
self.end_date = end_date
self._total_dates = self._get_all_dates()
def _get_all_dates(self) -> Iterator[date]:
current_day = self.start_date
while current_day <= self.end_date:
yield current_day
current_day += timedelta(days=1)
def __len__(self):
print("Calling the len function...")
return len(self._total_dates)
def __getitem__(self, index):
print(f"Calling getitem with value of index as {index}")
return self._total_dates[index]
if __name__ == "__main__":
date_iterator = DateIterator(date(2019, 1, 1), date(2019, 1, 15))
for new_date in …Run Code Online (Sandbox Code Playgroud) 有人可以帮我理解下面两段代码之间的区别.为什么两者的结果都不同.我在每种情况下选择相同的属性(名称):
代码1:
$obj = Get-Service | Where-Object {$_.Status -eq "Running"} | foreach-object {$_.Name} | select -first 3
foreach ( $item in $obj ) { write-output "Name is : $item" }
Output :
Name is : AeLookupSvc
Name is : Appinfo
Name is : AudioEndpointBuilder
Run Code Online (Sandbox Code Playgroud)
代码2:
$obj = Get-Service | Where-Object {$_.Status -eq "Running"} | select -first 3 name
foreach ( $item in $obj ) { write-output "Name is : $item" }
Output :
Name is : @{Name=AeLookupSvc}
Name is : …Run Code Online (Sandbox Code Playgroud) 根据我对 Python 面向对象编程的理解,如果一个类__call__定义了方法,如果我们像函数调用一样使用类的实例,就会调用该方法。例如:
class Employee:
def __init__(self,name,sal):
self.name = name
self.salary = sal
def __call__(self,value):
return self.salary * value
e = Employee("Subhayan",20000)
print (e(10))
Run Code Online (Sandbox Code Playgroud)
因此该__call__方法将对象实例作为第一个参数。
我只是想了解 Python 中的元类,我读到这type是所有用户定义类的默认元类。
如果我在 Python 中定义一个基本的自定义元类:
class Meta(type):
def __new__(meta, classname, supers, classdict):
# Run by inherited type.__call__
return type.__new__(meta, classname, supers, classdict)
Run Code Online (Sandbox Code Playgroud)
现在根据书中给出的文档,元类__new__方法将由__call__从类型继承的方法运行。
现在我的问题是使用__call__ 任何类的方法,我们必须拥有该类的对象,然后将其作为函数调用。
这里我们没有任何类型的对象来使用它的__call__功能。
有人可以向我解释一下__call__type class的功能是如何出现的吗?
我有以下用于创建线程和运行它们的代码。
from concurrent.futures import ThreadPoolExecutor
import threading
def task(n):
result = 0
i = 0
for i in range(n):
result = result + i
print("I: {}".format(result))
print(f'Thread : {threading.current_thread()} executed with variable {n}')
def main():
executor = ThreadPoolExecutor(max_workers=3)
task1 = executor.submit(task, (10))
task2 = executor.submit(task, (100))
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
当我在 Windows 10 机器上运行代码时,这是生成的输出:
I: 45
Thread : <Thread(ThreadPoolExecutor-0_0, started daemon 11956)> executed with variable 10
I: 4950
Thread : <Thread(ThreadPoolExecutor-0_0, started daemon 11956)> executed with variable 100
Process …Run Code Online (Sandbox Code Playgroud) 我有以下烧瓶代码:
from flask import Flask,request,jsonify
import requests
from werkzeug.exceptions import InternalServerError, NotFound
import sys
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = "Secret!"
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/test',methods=["GET","POST"])
def test():
url = "https://httpbin.org/status/404"
try: …Run Code Online (Sandbox Code Playgroud)