相关疑难解决方法(0)

使用__init __()方法理解Python super()

我正在努力了解它的用法super().从它的外观来看,可以创建两个子类,就好了.

我很想知道以下2个孩子班级之间的实际差异.

class Base(object):
    def __init__(self):
        print "Base created"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()

ChildA() 
ChildB()
Run Code Online (Sandbox Code Playgroud)

python oop inheritance class super

2366
推荐指数
7
解决办法
158万
查看次数

在Python中调用基类的类方法

请考虑以下代码:

class Base(object):

    @classmethod
    def do(cls, a):
        print cls, a

class Derived(Base):

    @classmethod
    def do(cls, a):
        print 'In derived!'
        # Base.do(cls, a) -- can't pass `cls`
        Base.do(a)

if __name__ == '__main__':
    d = Derived()
    d.do('hello')

> $ python play.py  
> In derived! 
> <class '__main__.Base'> msg
Run Code Online (Sandbox Code Playgroud)

Derived.do,我该如何打电话Base.do

super如果这是一个普通的对象方法,我通常会直接使用甚至是基类名,但显然我找不到在基类中调用classmethod的方法.

在上面的例子中,Base.do(a)print Base类而不是Derived类.

python overriding class class-method

93
推荐指数
2
解决办法
4万
查看次数

Python - 覆盖__init__的最干净的方法,在super()调用之后必须使用可选的kwarg?

我喜欢蟒蛇的外观/感觉如何美丽,我希望这可以更清洁(可读性很棒).

什么是清洁的方式来推翻子类时要接受一个可选的关键字参数初始化,其中可选的kwarg,必须使用super()电话吗?

我有一个django表单,我想接受一个可选的用户参数,但如果我将其定义为参数之一user=None,那么通常的表单调用form({})假定位置参数引用关键字参数user.

代码说得比(我)的话更好:

def __init__(self, *args, **kwargs):
    user = None
    if 'user' in kwargs:
        user = kwargs.pop('user')
    super(BaseCheckoutForm, self).__init__(*args, **kwargs)
    if user:
        self.prefill_from_user(user)
Run Code Online (Sandbox Code Playgroud)

通过查看实际的Form类来查看它正在查找的参数,我可以使它成为最干净的,但是在python中对子类进行子类化的最大好处之一就是收集所有args并将kwargs其传递给任何子类.此外,这不会影响源中的任何更改.

def __init__(self, querydict=None, user=None):
    super(BaseCheckoutForm, self).__init__(querydict)
    if user:
        self.prefill_from_user(user)
Run Code Online (Sandbox Code Playgroud)

但不幸的是我有:

 def __init__(self, *args, **kwargs):
    # cannot define user=None as an argument because normal usage
    # of class expects a certain order of positional args
    user …
Run Code Online (Sandbox Code Playgroud)

python django

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

如何在python中引用父方法?

假设我有两个类(一个是父类,一个是子类).如果在子类中定义的方法不同,我如何引用父类中的方法?

这是代码:

class A:
    def __init__(self, num):
        self.value=num
    def f(self, num):
        return self.value+2
class B(A):
    def f(self, num):
        return 7*self.f(num)
Run Code Online (Sandbox Code Playgroud)

在最后一行中,我想用"self.f(num)"命令引用父类A,而不是B中创建无限递归的方法本身.先感谢您.

python polymorphism inheritance

29
推荐指数
3
解决办法
6万
查看次数

在不更改其名称的情况下向父类方法添加额外功能

我有两个班,一个是父母,另一个是孩子.

class Parent(object):

    def __init__(self):
        #does something

    def method_parent(self):
        print "Parent"

class Child(Parent):

    def __init__(self):
        Parent.__init__(self)

    def method_parent(self):
        print "Child"
Run Code Online (Sandbox Code Playgroud)

继承父级后,我想修改Parent方法,method_parent保留该方法的原始功能,并为该方法添加一些额外的代码行.

我知道我可以创建一个新的方法

def method_child(self):
    self.method_parent()
    #Add extra lines of code to perform something 
Run Code Online (Sandbox Code Playgroud)

但我想使用方法的原始名称.我无法复制该方法的源代码,因为该方法来自C模块

我想要实现的是这样的

def method_parent():
    #do parent_method stuff
    #do extra stuff
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?

python class

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

如何在猴子修补时调用原始方法?

我在主项目中有一堂课,我不想改变.

class A():
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    def name(self):
        # this method could be much more complex
        return self.lastname.upper()
Run Code Online (Sandbox Code Playgroud)

我正在尝试构建一个插件mechansim.到目前为止,我有一个像这样的扩展点:

if __name__ == '__main__':
    ''' The main project has an extension point that allows me to do'''
    # for each class extension such as AExtended:
    A.name = AExtended.name
    ''' After the extensions are loaded, some behaviours may be changed'''
    a = A("John", "Doe")
    print(a.name())
Run Code Online (Sandbox Code Playgroud)

插件可以这样写:

class AExtended(A):
    ''' This is an extension I provide …
Run Code Online (Sandbox Code Playgroud)

python oop overriding monkeypatching python-3.x

10
推荐指数
2
解决办法
3674
查看次数

Python中没有构造函数重载 - 缺点?

我正在通过DiveIntoPython并遇到这个:

Java和Powerbuilder通过参数列表支持函数重载,即一个类可以有多个具有相同名称但不同数量的参数或不同类型的参数的方法.其他语言(最着名的是PL/SQL)甚至支持通过参数名称进行函数重载; 即一个类可以有多个方法具有相同的名称和相同数量的相同类型但不同的参数名称的参数.Python不支持这些; 它没有任何形式的函数重载.方法仅由它们的名称定义,并且每个类只有一个方法具有给定名称.因此,如果后代类具有__init__方法,则它始终会覆盖祖先__init__方法,即使后代使用不同的参数列表定义它也是如此.同样的规则适用于任何其他方法.

这不是一个主要的缺点,子类的__init__方法总是会覆盖超类的__init__方法吗?所以,如果我初始化一些变量和类调用一些功能class1__init__,然后我得到一个子类class2(class1)的话,我不得不重新初始化所有class1的变量,并调用这些功能class2__init__

我很确定我误解了这一切,所以如果有人澄清这一点,那就太好了.

python

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

如何将父类方法的内容添加到子类方法中

好吧我是OOP的新手,我的问题是我有这个父类,并且它有一个方法信息.我想在同一个方法中的子类内重用该方法中的两个print语句并添加更多信息.但我无法让它发挥作用

class company:

    def __init__(self, fName, lName, salary):

        self.fName = fName
        self.lName = lName
        self.salary = salary

    def info(self):
        print("Name:", self.fName, self.lName)
        print("Salary:", self.salary)

class programmers(company):
    def __init__(self, fName, lName, salary, progLang):

        super().__init__(fName, lName, salary)
        self.progLang = progLang

    def info(self):
        print("Programming language:", self.progLang)

programmer1 = programmers("John", "Doe", 1000, "Python")
programmer1.info()
Run Code Online (Sandbox Code Playgroud)

我想过只是重写我想要重用的代码行,但是我会考虑OOP.

我正在寻找这种输出......

Name: John Doe
Salary: 1000
Programming language: Python
Run Code Online (Sandbox Code Playgroud)

我正在使用Python 3

提前致谢!

python oop

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

从父类获取变量以用于子类的方法

我试图理解Python中的父类和子类如何工作,我遇到了这个看似简单的问题:

class parent(object):

    def __init__(self):
        self.data = 42


class child(parent):

    def __init__(self):
        self.string = 'is the answer!'

    def printDataAndString(self):
        print( str(self.data) + ' ' + self.string )


c = child()
c.printDataAndString()
Run Code Online (Sandbox Code Playgroud)

我期待字符串42就是答案!但我明白了

AttributeError:'child'对象没有属性'data'

我错过了什么?

我experimentated与pass和也super(parent,...),但不能得到它的权利.

python inheritance

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

Python 2.3调用超类方法

在以下Python 2.3脚本中调用基类函数时遇到问题.在审阅这篇文章后:

从Python中的子类调用父类的方法?

我生成了这小段代码:

class Base(object):

    def func(self):
        print "Base.func"

class Derived(Base):

    def func(self):
        super(Base, self).func()
        print "Derived.func"

Derived().func()
Run Code Online (Sandbox Code Playgroud)

上面的代码生成此错误:

Traceback (most recent call last):
  File "py.py", line 13, in ?
    Derived().func()
  File "py.py", line 10, in func
    super(Base, self).func()
AttributeError: 'super' object has no attribute 'func'
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

python derived-class super superclass

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

在 Python 中调用父类中的子方法

注意:这不是在子类中调用父方法 .super()

我有三个班级,比方说ParentChild1Child2Child1和 2 都有方法Cry()Parent类有另一个方法,例如MakeChildrenStopCry()在其中Cry()被调用。但是,Parent类没有方法Cry()。我需要Cry()Parent类中定义吗?

因为我没有父类的任何对象并且我总是使用子类,所以我只是创建了“空函数”,因为继承只会用Child类中的函数覆盖这些空函数。

def MakeChildrenStopCry(self):
   if self.Cry():
    self.DoWhateverToStopCry(self)
def Cry(self)
   return()
Run Code Online (Sandbox Code Playgroud)

对于完整的示例代码,您可以查看此内容,但我认为上述内容应该很清楚。

这不会在我的代码中造成任何问题,我只是想知道什么是正常完成的,或者以不同的方式设置我的代码是否更好。

python polymorphism inheritance class parent-child

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

如何在python中调用父类方法?

我正在用python编写一个类。

class my_class(object):
    def __init__(self):
    # build my objects 
    def foo(self,*args,**kwargs):
    # do something with them
Run Code Online (Sandbox Code Playgroud)

然后我想扩展这个类:

class my_extended_class(my_class):
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚访问父方法的正确方法是什么。

我可以吗:

1)创建一个父对象的实例?在构造函数时

def __init__(self):
    self.my_father=my_class()
    # other child-specific statements
    return self
def foo(self,*args,**kwargs):
    self.my_father.foo(*args,**kwargs)
    # other child-specific statements
    return self
Run Code Online (Sandbox Code Playgroud)

2)“直接”调用父方法?

def foo(self,*args,**kwargs):
    my_class.foo(*args,**kwargs)
    # other child-specific statements
    return self
Run Code Online (Sandbox Code Playgroud)

3)其他可能的方式?

python oop inheritance class

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