相关疑难解决方法(0)

python中的链调用父构造函数

考虑一下 - 基类A,继承自A的类B,继承自B的类C.什么是在构造函数中调用父类构造函数的通用方法?如果这仍然听起来太模糊,这里有一些代码.

class A(object):
    def __init__(self):
        print "Initialiser A was called"

class B(A):
    def __init__(self):
        super(B,self).__init__()
        print "Initialiser B was called"

class C(B):
    def __init__(self):
        super(C,self).__init__()
        print "Initialiser C was called"

c = C()
Run Code Online (Sandbox Code Playgroud)

这就是我现在这样做的方式.但它仍然看起来有点过于非泛型 - 您仍然必须手动传递正确的类型.

现在,我尝试使用self.__class__作为super()的第一个参数,但是,显然它不起作用 - 如果你把它放在C的构造函数中 - 公平,B的构造函数被调用.如果你在B中做同样的事情,"self"仍然指向一个C的实例,所以你最终再次调用B的构造函数(这以无限递归结束).

现在没有必要考虑钻石继承,我只想解决这个具体问题.

python oop inheritance constructor

279
推荐指数
3
解决办法
16万
查看次数

如何从子类调用Base Class的__init__方法?

如果我有一个python类:

class BaseClass(object):
#code and the init function of the base class
Run Code Online (Sandbox Code Playgroud)

然后我定义了一个子类,例如:

class ChildClass(BaseClass):
#here I want to call the init function of the base class
Run Code Online (Sandbox Code Playgroud)

如果基类的init函数接受一些我将它们作为子类的init函数的参数的参数,我该如何将这些参数传递给基类?

我写的代码是:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

python inheritance constructor python-2.7

89
推荐指数
4
解决办法
12万
查看次数

如何从Python中的继承类正确调用基类方法(和构造函数)?

假设我有一个继承自的Base类和Child类Base.从Python中的子类调用基类的构造函数的正确方法是什么?我用super吗?

这是我到目前为止的一个例子:

class Base(object):
   def __init__(self, value):
       self.value = value
   ...

class Child(Base):
   def __init__(self, something_else):
       super(Child, self).__init__(value=20)
       self.something_else = something_else
   ...
Run Code Online (Sandbox Code Playgroud)

它是否正确?

谢谢,Boda Cydo.

python

56
推荐指数
3
解决办法
5万
查看次数

如何在Django中返回401 Unauthorized?

而不是这样做:

res = HttpResponse("Unauthorized")
res.status_code = 401
return res
Run Code Online (Sandbox Code Playgroud)

有没有办法在不打字的情况下每次都这样做?

python django

45
推荐指数
5
解决办法
3万
查看次数

从python中的子类调用父类构造函数

所以,如果我有一个班级:

 class Person(object):
'''A class with several methods that revolve around a person's Name and Age.'''

    def __init__(self, name = 'Jane Doe', year = 2012):
        '''The default constructor for the Person class.'''
        self.n = name
        self.y = year
Run Code Online (Sandbox Code Playgroud)

然后这个子类:

 class Instructor(Person):
'''A subclass of the Person class, overloads the constructor with a new parameter.'''
     def __init__(self, name, year, degree):
         Person.__init__(self, name, year)
Run Code Online (Sandbox Code Playgroud)

我有点迷失了如何让子类调用并使用父类构造函数,name并在子类中year添加新参数degree.

python inheritance

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

Python抽象类应强制派生类在__init__中初始化变量

我想有一个抽象类,它强制每个派生类在其__init__方法中设置某些属性。

我已经看了几个不能完全解决我问题的问题,特别是在这里或这里。这看起来很有希望,但我无法使其正常运行。

我假设我想要的结果可能类似于以下伪代码:

from abc import ABCMeta, abstractmethod


class Quadrature(object, metaclass=ABCMeta):

    @someMagicKeyword            #<==== This is what I want, but can't get working
    xyz

    @someMagicKeyword            #<==== This is what I want, but can't get working
    weights


    @abstractmethod
    def __init__(self, order):
        pass


    def someStupidFunctionDefinedHere(self, n):
        return self.xyz+self.weights+n



class QuadratureWhichWorks(Quadrature):
    # This shall work because we initialize xyz and weights in __init__
    def __init__(self,order):
        self.xyz = 123
        self.weights = 456

class QuadratureWhichShallNotWork(Quadrature):
    # …
Run Code Online (Sandbox Code Playgroud)

python oop abstract-class

14
推荐指数
1
解决办法
689
查看次数

Python抽象方法,它有自己的__init__函数

如何__init__在基本抽象类和派生抽象类中定义函数并self.*在抽象方法中都可用?例如: 

利用在抽象类的基类中导入的函数的正确方法是什么?例如:在base.py中我有以下内容:

import abc

class BasePizza(object):
    __metaclass__  = abc.ABCMeta
    def __init__(self):
        self.firstname = "My Name"

    @abc.abstractmethod
    def get_ingredients(self):
         """Returns the ingredient list."""
Run Code Online (Sandbox Code Playgroud)

然后我在diet.py中定义方法:

import base

class DietPizza(base.BasePizza):
    def __init__(self):
        self.lastname = "Last Name"

    @staticmethod
    def get_ingredients():
        if functions.istrue():
            return True
        else:
            return False
Run Code Online (Sandbox Code Playgroud)

但是,当我运行时,diet.py我只能访问self.lastname.我想要DietPizza两个self.firstname和self.lastname.我怎样才能做到这一点?

python abstract-class abc python-3.x

3
推荐指数
1
解决办法
7653
查看次数

是否有必要在 python 中显式调用 super().__init__() ?

我来自 Java,在那里我们可以避免调用超类零参数构造函数。对它的调用是由编译器隐式生成的。

我读了这篇关于 super() 的文章,现在有疑问是否真的有必要明确地做这样的事情:

class A(object):
 def __init__(self):
   print("world")

class B(A):
 def __init__(self):
   print("hello")
   super().__init__() #Do we get some Undefined Behavior if we do not call it explicitly?
Run Code Online (Sandbox Code Playgroud)

python inheritance constructor class python-3.x

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

python 2.7-如何调用父类构造函数

我有下面的基类

class FileUtil:
    def __init__(self):
        self.outFileDir = os.path.join(settings.MEDIA_ROOT,'processed')
        if not os.path.exists(outFileDir):
            os.makedirs(outFileDir)
    ## other methods of the class
Run Code Online (Sandbox Code Playgroud)

我在扩展这个类,如下所示:

class Myfile(FileUtil):
    def __init__(self, extension):
        super(Myfile, self).__init__()
        self.extension = 'text'
    ## other methods of class
Run Code Online (Sandbox Code Playgroud)

但是我遇到错误了吗?

super(Myfile, self).__init__()
TypeError: super() takes at least 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)

我浏览了许多文档,发现在2.x和3.x中调用super()有不同的方式。我尝试了两种方式,但都出错了。

python python-2.7

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