1、简单例子

设计二维平面上的点类,实现移动、显示自己坐标、计算和其他对象之间欧式距离

from math import sqrt

class pointer:

    def __init__(self,x=0,y=0):
        self._x=x
        self._y=y

    def show(self):
        print(self._x,self._y)

    def  move(self,dx,dy):
        self._x+=dx
        self._y+=dy


    def move_to(self,x,y):
        self._x = x
        self._y = y


    def distance_to(self,other):
        return sqrt((self._x-other._x)**2+(self._y-other._y)**2)

    def __str__(self):
        return str(self._x)+','+str(self._y)

def main():
    p1=pointer(3,5)
    print(p1)
    p2=pointer()
    p1.move_to(4,3)
    print(p1.distance_to(p2))
    
if __name__=="__main__":
    main()

2、继承


class Person(object):
    def __init__(self, name, age,gender):
        self._name = name
        self._age = age
        self._gender=gender

    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age

    @property
    def gender(self):
        return self._gender

    def doing(self):
        if self._age<'19':
            print(self._name+" is studying!")
        else:
            print(self._name + " is working!")

class student(Person):
    def __init__(self, name, age,gender,nianji):
        super().__init__(name, age,gender)
        self._nianji=nianji

    def runing(self):
        print(self._name + " is running!")

def main():
    p1=Person('zhangsan','12','male')
    print(p1.gender)
    p1.doing()
    p4=student('lisi','14','female','chuyi')
    p4.doing()
    p4.runing()

if __name__=='__main__':
    main()

#输出
male
zhangsan is studying!
lisi is studying!
lisi is running!

3、多态

class Person(object):
    def __init__(self, name, age,gender):
        self._name = name
        self._age = age
        self._gender=gender

    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age

    @property
    def gender(self):
        return self._gender

    def doing(self):
        if self._age<'19':
            print(self._name+" is studying!")
        else:
            print(self._name + " is working!")

class student(Person):
    def __init__(self, name, age,gender,nianji):
        super().__init__(name, age,gender)
        self._nianji=nianji

    def runing(self):
        print(self._name + " is running!")

    def doing(self):#重写doing
        print(self._name + " is not studying!")

def main():
    p1=Person('zhangsan','12','male')
    print(p1.gender)
    p1.doing()
    p4=student('lisi','14','female','chuyi')
    p4.doing()
    p4.runing()

if __name__=='__main__':
    main()

#输出
male
zhangsan is studying!
lisi is not studying!
lisi is running!
Categories: Python

0 Comments

Leave a Reply

Your email address will not be published.