程序员python 高级码农成才之路

* 禁白嫖 * python-----类多态

2021-02-03  本文已影响0人  幼姿沫

#定义时的类型和运行时的类型不一致则为多态

class F1(object):

    def show(self):

        print('F1.show()')

class S1(F1):

    def show(self):

        print('S1.show()')

class S2(F1):

    def show(self):

        print('S2.show()')

def Func(obj):

    print(obj.show())

s1=S1()

print(type(s1))

Func(s1)

s2=S2()

print(type(s2))

Func(s2)

控制台输出结果

<class '__main__.S1'>

S1.show()

None

<class '__main__.S2'>

S2.show()

None

类属性、实例属性

'''

如果想要在类外修改类对象属性值,

实例化类对象之后进行赋值修改

'''

class People:

#类属性 可以用类名来引用

    body='idol'

    #对象属性 实例化类对象之后进行引用属性

    def __init__(self,name):

        self.name=name

        self.gender='male'

p=People('华晨宇')

print(p.name,p.body,p.gender)

#对对象的属性值进行修改直接赋值即可

p.body='singer'

print(p.body)

print(People.body)

控制台输出结果

华晨宇 idol male

singer

idol

静态方法和类方法

#修饰类的类方法用 @classmethod 类方法的参数为cls,实例化对象进行调用属性和方法

class Animal:

    def __init__(self,name='虎'):

        self.name=name

        self.eye='2只'

        self.color='orange'

    def eat(self):

        return '%s is eating' %self.name

class Panda(Animal):

    @classmethod

    def run(cls):

        return 'Panda is running'

p=Panda()

print('该动物是*',p.name,'动物的眼睛有*',p.eye,'动物的颜色是*',p.color)

print(p.run())

print(p.eat())

#用装饰器 @staticmethod静态方法来进行修饰  静态方法不需要多定义参数

#静态方法不需要参数 如果在静态方法中需要引用属性的话必须用类对象来引用

class People:

    country='China'

    @staticmethod

    def getCountry():

return People.country

p=People()

print(p.getCountry())

控制台输出结果展示

该动物是* 虎 动物的眼睛有* 2只 动物的颜色是* orange

Panda is running

虎 is eating

China

上一篇下一篇

猜你喜欢

热点阅读