相关疑难解决方法(0)

如何防止在python中重写函数

有没有办法让类函数不可重复?类似java的final关键字.即,任何重写类都不能覆盖该方法.

python overriding final

31
推荐指数
2
解决办法
1万
查看次数

使功能无法覆盖

我知道python函数默认是虚拟的.假设我有这个:

class Foo:
    def __init__(self, args):
        do some stuff
    def goo():
        print "You can overload me"
    def roo():
        print "You cannot overload me"
Run Code Online (Sandbox Code Playgroud)

我不希望他们能够做到这一点:

class Aoo(Foo):
    def roo():
        print "I don't want you to be able to do this"
Run Code Online (Sandbox Code Playgroud)

有没有办法防止用户超载roo()?

python

16
推荐指数
4
解决办法
3656
查看次数

定义Python类

我正在尝试自己学习Python,因此,我得到了一个用C#编写的软件,并试图用Python重新编写它.鉴于以下课程,我有几个问题:

C#

sealed class Message
{
    private int messageID;
    private string message;
    private ConcurrentBag <Employee> messageFor;
    private Person messageFrom;
    private string calltype;
    private string time;


    public Message(int iden,string message, Person messageFrom, string calltype,string time)
    {
        this.MessageIdentification = iden;
        this.messageFor = new ConcurrentBag<Employee>();
        this.Note = message;
        this.MessageFrom = messageFrom;
        this.CallType = calltype;
        this.MessageTime = time;
    }

    public ICollection<Employee> ReturnMessageFor
    {
        get
        {
            return messageFor.ToArray();
        }

    }
Run Code Online (Sandbox Code Playgroud)
  1. 在我的类中,我有一个名为messageFor的线程安全集合,在Python中是否存在等价物?如果是这样,我如何在python类中实现它?

  2. 我的线程安全集合也有一个吸气剂?我如何在Python中做同样的事情?

  3. Python有一个EqualsTo方法来测试对象之间的相等性吗?或者相当于Python中的这个?

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return …
    Run Code Online (Sandbox Code Playgroud)

c# python

5
推荐指数
1
解决办法
247
查看次数

有没有办法在继承期间持久化装饰器?

我正在尝试使用未实现的方法编写一个抽象类,这将强制继承子级在重写方法(在装饰器中定义)时返回特定类型的值。

当我使用下面显示的代码时,子方法不会调用装饰器。我认为这是因为该方法被覆盖,这很有意义。我的问题基本上是这样的:有没有办法通过方法覆盖使装饰器持久化?

我不反对使用装饰器以外的东西,但这是一个很快想到的解决方案,我很想知道是否有任何方法可以使它起作用。

如果使用装饰器是正确且可能的选择,它看起来像这样:

def decorator(returntype):
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            result = function(*args, **kwargs)
            if not type(result) == returntype:
                raise TypeError("Method must return {0}".format(returntype))
            else:
                return result
        return wrapper
    return real_decorator
Run Code Online (Sandbox Code Playgroud)

我需要我的父类看起来类似于这个:

class Parent(ABC):
    @decorator(int)
    @abstractmethod
    def aye(self, a):
        raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)

子类会做这样的事情:

class Child(Parent):
    def aye(self, a):
        return a
Run Code Online (Sandbox Code Playgroud)

如果需要,我很乐意更好地澄清我的问题,并感谢所有花时间提前阅读此问题的人!

python python-3.x python-decorators

5
推荐指数
1
解决办法
277
查看次数

标签 统计

python ×4

c# ×1

final ×1

overriding ×1

python-3.x ×1

python-decorators ×1