python OOP(2)

调用方法有两种形式

实例调用

直接调用后序参数即可

类调用

调用时需要先加上实例

示例

class test1:
    def pt(self,txt): #定义函数
        test1.txt=txt
        print(self.txt)
x=test1() #定义实例
x.pt('test') #实例调用
test1.pt(x,'test1') #类调用

定制被继承的方法

首先需要说明默认继承是你如果不去重载那么就是父类的,如果重载那么全部重来

比如继承构造如果不重载我们继承的就是父类的构造方法

示例

class test2:
    def __init__(self,x,y):
        test2.x=x
        test2.y=y
    def __str__(self):
        return 'x=%d y=%d' %(test2.x,test2.y)
x1=test2(1,2)
class test3(test2):
    def __str__(self):
        return 'y=%d x=%d' %(test3.y,test3.x)
x2=test3(1,2)
print(x1)
print(x2)

但是我们如果想子类扩充一些父类的构造的话,按照原来的套路我们需要把父类的再写一遍而不是直接补充

这里我们可以定制被继承的方法

说的这么高大上实际上就是把被继承的方法复读一遍。。。。

示例

class test2:
    def __init__(self,x,y):
        test2.x=x
        test2.y=y
    def __str__(self):
        return 'x=%d y=%d' %(test2.x,test2.y)
x1=test2(1,2)
class test3(test2):
    def __init__(self,x,y,z):
        test2.__init__(self,x,y)
        test3.z=z
    def __str__(self):
        return 'y=%d x=%d z=%d' %(test3.y,test3.x,test3.z)
x2=test3(1,2,3)
print(x1)
print(x2)

这也可以用在别的地方

示例

class test2:
    def __init__(self,x,y):
        test2.x=x
        test2.y=y
    def pt(self):
        print('x=%d y=%d' %(test2.x,test2.y))
x1=test2(1,2)
class test3(test2):
    def __init__(self,x,y,z):
        test2.__init__(self,x,y)
        test3.z=z
    def pt(self):
        test2.pt(self)
        print( 'z=%d' %(test3.z))
        test2.pt(self)
x2=test3(1,2,3)
x1.pt()
x2.pt()

输出(省略x,y,z)

1 2
1 2
3
1 2

这种方法好像对于运算符重载来说么得用,好像因为运算符直接return?(存疑)

接口定义(目前太菜完全不理解为啥这么做)

在父类中定义一个预计要在子类中出现得对象函数

示例

class test4:
    def pt(self):
        self.pt1()
class test5(test4):
    def pt1(self):
        print('这是一个接口?')
x3=test5()
x3.pt()

首先在父类中定义了一个子类得pt接口输出用子类得pt1()

然后定义有pt1的子类

然后定义子类的对象

直接调用这个接口

posted @ 2019-01-09 19:28  baccano!  阅读(138)  评论(0编辑  收藏  举报