Discuss / Python / 自己的一点理解,请指教

自己的一点理解,请指教

Topic source
class S:
    def __init__(self,looks):
        self.looks=looks
    def run1(self):
        print('she looks %s'% self.looks)

class S1(S):
    def __init__(self,looks,character):
        super().__init__()
        self.character=character
    def run2(self):
        print('she is not only %s, but also %s'%(self.looks,self.character))

class Lin:
    def run1(self):
        print('I am MK!')
    def run2(self):
        print('I love xinhui!')

def ling(g):
    g.run1()
    g.run2()


xinhui=S1('beautifui','gentle')
i=Lin()
ling(xinhui)
ling(i)

运行ling(xinhui)报错,super()函数难道不可以吗? TypeError: init() missing 1 required positional argument: 'looks'

losunlight

#13 Created at ... [Delete] [Delete and Lock User]

不错不错

wozhao我科

#14 Created at ... [Delete] [Delete and Lock User]

@迷茫的老九 改成:

super().init(looks)

@蓝色阳光一号

说点我的理解: 针对楼主代码而言 如果是静态语言,传入的参数类型必须是Province或者其子类 而Python的“鸭子类型”只要有ps、ps1方法的类都可以作为参数被传入 从而用这个例子说明了所谓的”鸭子类型“

yia宁

#16 Created at ... [Delete] [Delete and Lock User]

楼上的那位,报错很明显,父类的初始化要求有一个参数,加上就行了,

lass S1(S):
    def __init__(self, looks, character):
        super().__init__(looks) # 这里
        self.character = character

    def run2(self):
        print('she is not only %s, but also %s' % (self.looks, self.character))

mr911

#17 Created at ... [Delete] [Delete and Lock User]

道理我都懂...但是浦东成个市了?

阳光明媚-M

#18 Created at ... [Delete] [Delete and Lock User]

一楼正解,建议将x换成City,这样楼上的几位的疑问可以消了吧

阳光明媚-M

#19 Created at ... [Delete] [Delete and Lock User]

@迷茫的老九 其实这个初始化,没必要这么体现出继承,因为体现继承的部分在你定义的类的括号里面就已经体现了,比如class Student(People),这里就已经很明确的体现出继承了。所以,没必要那个“super().init()”,直接self.looks = looks即可(而且还显得很对称[摊手])


  • 1
  • 2

Reply