Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

class OldboyPeople:

"""由于学生和老师都是人,因此人都有姓名、年龄、性别"""
school = 'oldboy'

def __init__(self, name, age, gender):
    self.name = name
    self.age = age
    self.gender = gender
    

class OldboyStudent(OldboyPeople):

def choose_course(self):
    print('%s is choosing course' % self.name)
    

class OldboyTeacher(OldboyPeople):

def score(self, stu_obj, num):
    print('%s is scoring' % self.name)
    stu_obj.score = num

stu1 = OldboyStudent('tank', 18, 'male')
tea1 = OldboyTeacher('nick', 18, 'male')
tea1.score(stu1, 99)

比如这段代码里面,为什么tea1用自己的score方法,第一个参数必须要是stu1对象,还有stu_obj.score = num 这句没看懂,自己的参数调用自己?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

  • 第1个问题

为什么tea1用自己的score方法,第一个参数必须要是stu1对象?
第一个参数不是必须是stu1对象,你可以在你的代码下面加上下面的代码试试

class A():
    pass
 
a = A()
tea1.score(a, 99)

上面的代码是OK的!

  • 第2个问题

stu_obj.score = num 这句没看懂,自己的参数调用自己?
首先你要明确stu_obj是一个对象,在你的例子中它是一个OldboyStudent对象,我的第1个问题中是A类的对象,其实在python中,万物皆对象。
stu_obj.score = num的意思你的理解有些问题,它有两层基础含义:

  1. 如果stu_obj对象没有score这个属性,则为这个stu_obj对象创建一个属性叫score,并初始化为num,其类型与num一致
  2. 如果stu_obj对象score这个属性,则将他更新为num,其类型任然与num一致,不管score原来是什么类型,这里score会被直接替换为num,如:
class OldboyTeacher(OldboyPeople):

    def score(self, stu_obj, num):
        print('%s is scoring' % self.name)
        stu_obj.score = num
        print(stu_obj.score)


class A():
    def __init__(self):
        self.score = ()


if __name__ == '__main__':
    stu1 = OldboyStudent('tank', 18, 'male')
    tea1 = OldboyTeacher('nick', 18, 'male')
    tea1.score(A(), 99)

这里面还涉及一些其它python的相关的东西,由于篇幅,我就不多解释了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...