laoshi

Python3 类方法总结

  • 普通方法:对象访问
  • ç§�有方法:两个下划线开头,å�ªèƒ½åœ¨ç±»å†…部访问
  • é�™æ€�方法:类和对象访问,ä¸�能和其他方法é‡�å��,ä¸�然会相互覆盖,å�Žé�¢å®šä¹‰çš„会覆盖å‰�é�¢çš„
  • 类方法:类和对象访问,ä¸�能和其他方法é‡�å��,ä¸�然会相互覆盖,å�Žé�¢å®šä¹‰çš„会覆盖å‰�é�¢çš„
  • 多继承情况下:从左到å�³æŸ¥æ‰¾æ–¹æ³•,找到为止,ä¸�然就抛出异常
class People:

    # 定义基本属性
    name=''
    age=0
    # 定义�有属性外部无法直接访问
    __weight=0
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say : i am %d."%(self.name,self.age))
p = People('Python',10,20)
p.speak()
# __weight无法直接访问
print(p.name,'--',p.age)#,'--',p.__weight)

继承

�继承:

class Student(People):
    grade=''
    def __init__(self,n,a,w,g):
        People.__init__(self,n,a,w)
        self.grade = g

    # 覆写父类方法
    def speak():
        print("%s 说: 我 %d �了,我在读 %d 年级"%(self.name,self.age,self.grade))

class Speak():
    topic=''
    name=''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    # 普通方法,对象调用
    def speak(self):
        print("我� %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))

    # �有方法,self调用
    def __song(self):
        print('唱一首歌自己�',self);

    # ��方法,对象和类调用,�能和其他方法��,�然会相互覆盖,��定义的会覆盖��的
    @staticmethod
    def song():
        print('唱一首歌给类�:��方法');

    # 普通方法,对象调用
    def song(self):
        print('唱一首歌给你们�',self);
        
    # 类方法,对象和类调用,�能和其他方法��,�然会相互覆盖,��定义的会覆盖��的
    @classmethod
    def song(self):
        print('唱一首歌给类�:类方法',self)

多继承:

class Sample(Speak,Student):
    a = ''
    def __init__(self,n,a,w,g,t):
        Student.__init__(self,n,a,w,g)
        Speak.__init__(self,n,t)
test = Sample('Song',24,56,7,'Python')
test.speak()
test.song()
Sample.song()
Sample.song()
test.song()

# test.__song() 无法访问�有方法