Python生活不易 我用python

类和对象(基础应用)

2018-07-31  本文已影响156人  GHope

1.声明一个电脑类:
属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频

a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性

class Computer:
    __slots__ = ('self', 'brand', 'color', 'rom', 'mb', 'gd')

    def __init__(self, brand='MACHENIKE', color='gray', rom='2T'):
        self.brand = brand
        self.color = color
        self.rom = rom

    def play_game(self):
        print('Playing game!')

    def write_code(self):
        print('Writing code!!!')

    def watch_film(self):
        print('Watching film!!')

    def __str__(self):
        return 'brand: %s\tcolor: %s\trom: %s' % (self.brand, self.color, self.rom)


cpt1 = Computer()
print(cpt1.brand, cpt1.color, cpt1.rom)
cpt1.color = 'red'
cpt1.mb = '6G'
print(cpt1.mb)
del cpt1.mb
print(cpt1)


setattr(cpt1, 'color', 'black')
print(getattr(cpt1, 'color', '查无此讯'))
setattr(cpt1, 'gd', 'GTX1060')
print(getattr(cpt1, 'gd', '查无此讯'))
# delattr(cpt1, 'gd') #AttributeError: gd
print(cpt1)


运行结果:
MACHENIKE gray 2T
6G
brand: MACHENIKE    color: red  rom: 2T
black
GTX1060
brand: MACHENIKE    color: black    rom: 2T



class ComputerTeacher:
    """电脑类"""

    def __init__(self, brand='', color='black', memory=0):
        self.brand = brand
        self.color = color
        self.memory = memory

    """静态"""

    @staticmethod
    def play_game(game):
        print('打%s游戏' % game)

    @staticmethod
    def coding(code_type):
        print('写%s程序' % code_type)

    @staticmethod
    def watch_video(video):
        print('在看%s' % video)


cm = ComputerTeacher()
cm.memory = 512
cm.brand = '惠普'
ComputerTeacher.play_game('贪吃蛇')
# cm.price = 998
setattr(cm, 'price', 998)
print(cm.price)

# del cm.price
cm.__delattr__('price')

2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄

class Dog:
    def __init__(self, name='大黄', color='yellow', age='3'):
        self.name = name
        self.color = color
        self.age = age

    def bark(self):
        print('%s is barking.' % self.name)

    def __str__(self):
        return self.name


class Person:
    def __init__(self, name='', age='18', dog=''):
        self.name = name
        self.age = age
        self.dog = dog

    def walk_with_dog(self, dog):
        print('%s walk with %s.' % (self.name, dog))


dog1 = Dog()
p1 = Person('小明', dog=dog1)
p1.walk_with_dog(dog1)
dog1.bark()

运行结果:
小明 walk with 大黄.
大黄 is barking.


class DogTeacher:
    """狗类"""

    def __init__(self, name='', color='yellow', age=0):
        self.name = name
        self.color = color
        self.age = age

    def shout(self):
        print('%s :汪汪汪!!!' % self.name)


class PersonTeacher:
    """人类"""

    def __init__(self, name, age):
        self.name = name
        self.age = age
        # None来表示对象的零值
        self.dog = None

    def walk_the_dog(self):
        """遛狗"""
        if self.dog == None:
            print("没狗,遛自己吧!")
            return

        print('%s牵着%s在散步' % (self.name, self.dog.name))

pe1 = PersonTeacher('小明',18)
# pe1.dog = Dog('大黄')
pe1.walk_the_dog()

3.声明一个矩形类:
属性:长、宽
方法:计算周长和面积
a.创建不同的矩形,并且打印其周长和面积

class Rectangle:
    def __init__(self, w, h):
        self.width = int(w)
        self.hight = int(h)

    def __str__(self):
        return '周长:%d\t 面积: %d' % (int(2 * (self.hight + self.width)), int(self.width * self.hight))


r1 = Rectangle(2, 4)
print(r1)
r2 = Rectangle(3, 6)
print(r2)

运行结果:
周长:12    面积: 8
周长:18    面积: 18


class RectangleTeacher:
    """矩形类"""

    def __init__(self, length, width):
        self.length = length
        self.width = width

    def perimeter(self):
        """求周长"""
        return (self.width + self.length) * 2

    def area(self):
        """求面积"""
        return self.length * self.width


# 函数式考虑参数,面向对象考虑对象

re1 = RectangleTeacher(10, 20)
print(re1.perimeter(), re1.area())

4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名

class Studet:
    def __init__(self, name='GHope', age=18, number=''):
        self.name = name
        self.age = age
        self.number = number

    def called(self):
        print("%s:到!" % (self.name))

    def diaplay_all(self):
        print('姓名:%s,年龄 %s,学号:%s' % (self.name, self.age, self.number))


class Class:
    def __init__(self, stu=[], className='py1805'):
        self.stu = stu
        self.class_name = className

    def add_stu(self):
        name = input('name\t')
        age = input('age\t')
        number = input('number\t')
        stu1 = Studet(name, int(age), number)
        self.stu.append(stu1)

    def del_stu(self, name):  # 删除学生姓名
        for student in self.stu[:]:
            if name == student.name:
                self.stu.remove(student)

    def call_stu(self):
        for student in self.stu[:]:
            print(student.name)
            student.called()

c1 = Class()
c1.add_stu()
c1.call_stu()


运行结果:
name    GHope
age 18
number  23
GHope
GHope:到!



from random import randint


class StudentTeacher:
    """学生类"""

    def __init__(self, name='', age=''):
        self.name = name
        self.age = age
        self.study_id = 'py1805' + str(randint(0, 50))

    def answer(self):
        print('%s ,到!' % self.name)

    def show(self):
        print('姓名:%s,年龄:%s,学号:%s' % (self.name, self.age, self.study_id))


class ClassTeacher:
    """班级类"""

    def __init__(self, name=''):
        self.name = name
        self.students = []

    def append_student(self, student=None):
        """添加学生"""
        self.students.append(student)

    def del_student(self, name):
        for student in self.students[:]:
            if student.name == name:
                self.students.remove(student)

    def call_names(self):
        """点名"""
        for student in self.students:
            """点名"""
            print(student.name)
            """答到"""
            student.answer()


stut1 = StudentTeacher('张三', 20)
stut2 = StudentTeacher('李四', 18)
stut3 = StudentTeacher('王五', 22)
clst1 = ClassTeacher('py1805')
clst1.append_student(stut1)
clst1.append_student(stut2)
clst1.append_student(stut3)

clst1.call_names()


结果:
张三
张三 ,到!
李四
李四 ,到!
王五
王五 ,到!

注意:如果函数的参数是对象(列表、字典、类的对象),传参的时候传的是地址。如果需要对对象的内容进行修改,传参的时候传对象的拷贝(列表的切片)

5.写一个类,封装所有和数学运算相关的功能(包含常用功能和常用值,例如:pi, e等)

"""
import math


class Operation:#数学类无实例,所有方法及内容都属于类的方法和类的字段
    def __init__(self):
        self.pi = math.pi
        self.e = math.e

    def add(self,x,y):
        return x+y

    def minus(self,x,y):
        return x-y

    def multiply(self,x,y):
        return x*y

    def divide(self,x,y):
        return x/y

"""
class MathTeacher:
    """数学类"""
    pi = 3.1415926
    e = 2.718

    @staticmethod
    def sum(*number):
        """求和"""
        sum1 = 0
        for x in number:
            sum1 += x

        return sum1

    @classmethod
    def cricle_area(cls, radius):
        """求圆的面积"""
        return radius ** 2 * cls.pi


print(MathTeacher.sum(10, 2, 3))
print(MathTeacher.cricle_area(5))

运行结果:
15
78.539815

6.1.写一个班级类,属性:班级名、学生;功能:添加学生、删除学生、根据姓名查看学生信息,展示班级的所有学生信息

class Class1:
    def __init__(self, clsname, stu=[]):
        self.clsname = clsname
        self.stu = stu

    def add_stu(self):
        name = input('name\t')
        age = input('age\t')
        number = input('number\t')
        stu1 = Studet(name, int(age), number)
        self.stu.append(stu1)

    def del_stu(self, name):  # 删除学生姓名
        for student in self.stu:
            if student.name == name:
                self.stu.remove(student)

    def find_stu(self, name):
        for student in self.stu:
            if student.name == name:
                print(student)

    def find_all_stu(self):
        for student in self.stu:
            print(student)

运行结果:
name    GHope
age 18
number  123
<__main__.Studet object at 0x00000246D8AD2EB8>
<__main__.Studet object at 0x00000246D8AD2EB8>
#因为没有重写前面的Student类中的str方法,所以输出为地址。

上一篇下一篇

猜你喜欢

热点阅读