找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2363|回复: 1

[代码与实例] python 类的继承子类显示有问题

2

主题

2

帖子

2

积分

贫民

积分
2
xiyueyys 发表于 2020-3-12 23:38:33 | 显示全部楼层 |阅读模式


Tim 说: 我 25 岁 tizhong 80 爱好 <__main__.people object at 0x7fa7ea1e2860> 。
想问下  为什么 子类继承pepole 类后 luxing 的结果变了呢?


class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w,p):
        self.name = n
        self.age = a
        self.__weight = w
        self.aihao = p
    def pspeak(self):
        print("%s 说: 我 %d 岁 tizhong %d 爱好 %s 。" %(self.name,self.age,self.__weight,self.aihao))
p = people('yys',18,180,"wan")
p.pspeak()

#另一个类,多重继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))

#多重继承
class sample(people,speaker): #继承speaker和student类

    def __init__(self,n,a,w,g,t):
        #student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)
        people.__init__(self,n,a,w,p)

test = sample("Tim",25,80,"luxing","python")
test.speak()   #方法名同,speak就是方法,默认调用的是在括号中排前地父类的方法
test.pspeak()


执行后:
yys 说: 我 18 岁 tizhong 180 爱好 wan 。我叫 Tim,我是一个演说家,我演讲的主题是 pythonTim 说: 我 25 岁 tizhong 80 爱好 <__main__.people object at 0x7fa7ea1e2860> 。
想问下  为什么 子类继承pepole 类后 luxing 的结果变了呢?


回复

使用道具 举报

0

主题

3

帖子

3

积分

贫民

积分
3
zbnzbn 发表于 2020-3-20 22:42:01 | 显示全部楼层
people.__init__(self,n,a,w,p)
这里的参数p 错了,应该是g
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表