这是针对这个问题的答案"使用python的abc模块来创建抽象类".(由@alexvassel作为答案接受).
我尝试了这些建议,但奇怪的是,尽管遵循了使用abc方式的建议,但它对我不起作用.因此我在这里将其作为一个问题发布:
这是我的Python代码:
from abc import ABCMeta, abstractmethod
class Abstract(object):
__metaclass__ = ABCMeta
@abstractmethod
def foo(self):
print("tst")
a = Abstract()
a.foo()
Run Code Online (Sandbox Code Playgroud)
当我执行这个模块时,这是我控制台上的输出:
pydev debugger: starting (pid: 20388)
tst
Run Code Online (Sandbox Code Playgroud)
而不是那个被接受的答案
>>> TypeError: Can not instantiate abstract class Abstract with abstract methods foo
Run Code Online (Sandbox Code Playgroud)
那我在做什么是对还是错?为什么工作而不是失败?感谢任何专家对此的见解.
python abstract-class python-2.x abstract-base-class python-3.x
我想为Symfony中的所有控制器创建一个基本控制器类,我是Symfony的新手,所以不要对愚蠢的问题生气.我问这个问题,因为我不能做这样的事情
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class AbstractController extends Controller
{
public function __construct()
{
//...... check access level
$user = $this->getUser(); //This is not working, I don't have access to the Controller(the base class) properties
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的一个控制器
class UserController extends AbstractController
{
public deleteUserAction(Request $request)
{
var_dump($this);// this will dump an empty class that is not instance of Symfony\Bundle\FrameworkBundle\Controller\Controller
//.... delete user
}
}
Run Code Online (Sandbox Code Playgroud)
做这个的最好方式是什么?请...编辑....我真正想要做的是检查用户权限级别是否足以访问特定控制器中的特定操作(例如deleteUserAction())(例如UserController),我有一个类将权限级别附加到所有控制器中的所有操作.如果它发生在父控制器(例如BaseController的构造函数)中,那么检查将非常有效,该控制器之前执行UserController->deleteUserAction()但在基本控制器中我无法访问$ this.我试过选民和ACL没有人帮助我的情况.提前致谢.
我正在尝试定义一个类,该类将另一个类作为属性_model并将实例化该类的对象。
from abc import ABC
from typing import Generic, TypeVar, Any, ClassVar, Type
Item = TypeVar("Item", bound=Any)
class SomeClass(Generic[Item], ABC):
_model: ClassVar[Type[Item]]
def _compose_item(self, **attrs: Any) -> Item:
return self._model(**attrs)
Run Code Online (Sandbox Code Playgroud)
self._model(**attrs)我认为返回 , 的实例应该是显而易见的Item,因为_model被显式声明为Type[Item]并被attrs声明为Dict[str, Any]。
但我从中得到的mypy 0.910是:
test.py: note: In member "_compose_item" of class "SomeClass":
test.py:11: error: Returning Any from function declared to return "Item"
return self._model(**attrs)
^
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
(我使用的是python 2.7)python文档表明你可以将映射传递给内置的dict,它会将该映射复制到新的dict中:
http://docs.python.org/library/stdtypes.html#mapping-types-dict
我有一个实现Mapping ABC的类,但它失败了:
import collections
class Mapping(object):
def __init__(self, dict={}): self.dict=dict
def __iter__(self): return iter(self.dict)
def __iter__(self): return iter(self.dict)
def __len__(self): return len(self.dict)
def __contains__(self, value): return value in self.dict
def __getitem__(self, name): return self.dict[name]
m=Mapping({5:5})
dict(m)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: cannot convert dictionary update sequence element #0 to a sequence
collections.Mapping.register(Mapping)
dict(m)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# …Run Code Online (Sandbox Code Playgroud) 我有一类以下设计:
class Meal {
public:
virtual void cook() = 0; // pure virtual
}
class Omelette : Meal {
public:
void cook() {/*do something*/}; // non-virtual
}
class Waffle : Meal {
public:
void cook() {/*do something*/}; // non-virtual
}
std::vector< std::unique_ptr<Meal> > menu;
void addMeal(const Meal& meal) {
menu.emplace_back(new Meal(meal)); // cannot allocate an object of abstract type
}
Run Code Online (Sandbox Code Playgroud)
我无法找到将Meal-derived对象添加到中的方法,menu因为我无法创建抽象对象。有没有一种执行上述代码的方法?我希望Meal保持抽象。我可以传递一个指向现有Meal派生对象的指针,但是然后我的unique_ptr几乎不是唯一的。
我想开始在我的C++代码中添加一些接口,以便我更容易使用模拟进行单元测试.
这个问题是从C++中的方法返回抽象类是一件痛苦的事.您不能按值返回,因此您需要返回指针或引用.
考虑到过去六七年中C++的所有发展,我想我会问是否有更好的方法来返回抽象基类.没有噪音的接口看起来像这样,但我确信这是不可能的.
IBaseInterface getThing() {return DerivedThing{};}
Run Code Online (Sandbox Code Playgroud)
我记得在过去这样做的方式是使用指针(现在可能是智能指针):
std::unique_ptr<IBaseInterface> getThing() {return std::make_unique<DerivedThing>();}
Run Code Online (Sandbox Code Playgroud)
指针的问题在于我实际上从未计划利用nullptr,因此处理指针而不是值的开销和噪音不会使读者没有价值.
有没有更好的方法,我不知道处理这个?
c++ interface abstract-base-class return-value-optimization c++17
给定使用CRTP的基类,我正在研究在基模板类中声明一个成员,其中类型取决于派生类。
尽管以下各项按预期工作:
template <class T> class BaseTraits;
template <class T> class Base {
using TypeId = typename BaseTraits<T>::TypeId;
TypeId id;
public:
Base() { id = 123; }
TypeId getId() { return id; }
};
class Derived;
template <> class BaseTraits<Derived> {
public:
using TypeId = int;
};
class Derived : public Base<Derived> {};
int main(int argc, char ** argv) {
Derived foo;
return foo.getId();
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以简化实施。我可以在模板中添加第二个模板参数Base,并使其BaseTraits更简单甚至摆脱它。但是,以上代码段已经尝试删除第二个模板参数。我正在寻找不涉及的第二个模板参数的解决方案Base。
我已经尝试过类似以下内容的方法,但是无法编译:
错误:无效使用不完整类型“派生类”
template <class T> class Base { …Run Code Online (Sandbox Code Playgroud) 据我所知,Python 模块 abc 应该防止类的实例化,这些类没有@abstractmethod实现基类的所有标记方法(前提是基类已经__metaclass__ = ABCMeta设置)
但是,这似乎不适用于以下代码:
抽象基类:
""" Contains payment processors for executing payments """
from abc import ABCMeta, abstractmethod
class AbstractPaymentProcessor:
""" Abstract class for executing faucet Payments
Implement this at your own. Possible implementations include
online wallets and RPC calls to running dogecoin wallets """
__metaclass__ = ABCMeta
@abstractmethod
def execute_payment(self, destination_address, amount):
""" Execute a payment to one receiving single address
return the transaction id or None """
pass
@abstractmethod
def execute_multi_payment(self, …Run Code Online (Sandbox Code Playgroud) 通过抽象基类,Python 提供了一种无需实际尝试即可了解对象行为的方法。在标准库中,我们为collections.abc 中的容器定义了一些 ABC 。例如,可以测试一个参数是否可迭代:
from collections.abc import Iterable
def function(argument):
if not isinstance(argument, Iterable):
raise TypeError('argument must be iterable.')
# do stuff with the argument
Run Code Online (Sandbox Code Playgroud)
我希望有一个这样的 ABC 来决定是否可以比较一个类的实例但找不到一个。测试__lt__方法的存在是不够的。例如,字典不能比较,但__lt__仍然是定义的(与object实际相同)。
>>> d1, d2 = {}, {}
>>> d1 < d2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()
>>> hasattr(d1, '__lt__')
True
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:有没有一种简单的方法来做到这一点,而无需自己进行比较并捕捉到 TypeError?
我的用例类似于排序的容器:我想在插入第一个元素时引发异常,而不是等待第二个元素。我想过将元素与其自身进行比较,但有没有更好的方法:
def insert(self, element):
try:
element < …Run Code Online (Sandbox Code Playgroud) 在Python 3.6中,我试图在AbstractBaseClass中定义一个属性; 我的第一次尝试是这样的(后来我发现我可以省略@staticmethod):
class AnAbstractClass(ABC):
@property
@staticmethod
@abstractmethod
def my_property():
pass
Run Code Online (Sandbox Code Playgroud)
据我所知,@staticmethod装饰器不返回可调用但不同的东西.(我怀疑这也导致mypy在我的代码中的返回值类型上引发错误,但是我无法在较小的代码示例中重现该问题).
这里发生了什么?
python ×6
c++ ×3
python-3.x ×2
abc ×1
c++11 ×1
c++17 ×1
controller ×1
crtp ×1
interface ×1
mypy ×1
php ×1
pycharm ×1
python-2.x ×1
python-3.6 ×1
subclass ×1
symfony ×1
templates ×1
type-hinting ×1