Python ---- Experiment 6

8. Regarding attributes, the following statement is correct ().
A. Data members are also called attributes and are divided into public attributes and private attributes.
B. In order not to destroy the encapsulation of the class, you can use the @property decorator to access private properties and check the properties.
C. @property decorator is a special property, which is responsible for calling a method into a property.
D. Setter This decorator allows assignment to properties (functions) decorated with @property, but the setter decorator must be behind the property, and the names of the two decorated properties (functions) must be the same.

9. Judgment: Private members cannot be directly accessed from outside the class, and are generally accessed and operated within the class. In a special way, "object name._class name __xxx" can also access private members in external programs, but this will destroy the encapsulation of the class and is not recommended.

Answer: Yes

10. Design a simple calculator for the monthly mortgage payment of home buyers, and calculate the total interest and monthly repayment amount according to the following formula:

Total interest = loan amount * interest rate
Monthly repayment amount = (loan amount + total interest) /
loan period Different loan periods have different interest rates. Here, there are only three kinds of years and interest rates as shown in the following table. Annual
interest rate
3 years (36 months) 6.03%
5 years (60 months) 6.12%
20 years (240 months) 4.39%

class LoanCaculator():
    def __init__(self, loan, time):
        self.loan = loan
        if time == "1":
            self.time = 3
        elif time == "2":
            self.time = 5
        elif time == "3":
            self.time = 20
    def get_total_interests(self):
        return self.loan * self.get_interests_rate()
    def get_interests_rate(self):
        if self.time == 3:
            return 0.0603
        elif self.time == 5:
            return 0.0612
        elif self.time == 20:
            return 0.0639
    def get_monthly_payment(self):
        return (self.loan + self.get_total_interests())/ (self.time * 12)

                                  

loan = int(input("请输入贷款金额:"))
time = input("请选择贷款年限:1.3年(36个月) 2.5年(60个月) 3.20年(240个月)")
loan_caculate = LoanCaculator(loan, time)
print("月供为: %f" % loan_caculate.get_monthly_payment())

Operation result:
Please enter the loan amount: 10000

Please select the loan period: 1.3 years (36 months) 2.5 years (60 months)
3.20 years (240 months) March supply: 44.329167

11. Design Bird and fish classes, both inherited from Animal class, implement its method print_info (), output information.

class Animal():
    def __init__(self,age):
        self.age = age
    def print_info(self):
        print("我今年%d岁了!" % (self.age))
class Bird(Animal):
    def __init__(self, color):
        super().__init__(4)
        self.color = color
    def print_info(self):
        print("我是一只%s的鸟" % (self.color))
        super().print_info()
class Fish(Animal):
    def __init__(self, weight):
        super().__init__(2)
        self.weight = weight
    def print_info(self):
        print("我是一只%d斤重的鱼" % (self.weight))
        super().print_info()
bird = Bird("红色")
bird.print_info()
fish =Fish(5)
fish.print_info()

Running result:
I am a red bird
I am 4 years old this year!
I am a fish with a weight of 5 kg.
I am 2 years old this year!

12. Use polymorphism to programmatically create a phone class Phones and define the call method call (). Create two subclasses: Apple phone class iPhone and Android phone class APhone, and override the method call in their respective classes. Create a human Person and define the method to call using a phone use_phone_call ()

class Phone():
    def call(self):
        print("使用功能机打电话")
class IPhone(Phone):
    def call(self):
        print("使用苹果手机打电话")
class APhone(Phone):
    def call(self):
        print("使用安卓手机打电话")
class Person():
    def use_phone_call(self, phone):
        phone.call()
person = Person()
person.use_phone_call(Phone())
person.use_phone_call(IPhone())
person.use_phone_call(APhone())

Operation result:
using a feature phone to make a call
using an Apple mobile phone to make a call
using an Android mobile phone

3 PUBG game

(1) Define Player variables: name, blood (health), weapon (weapon) methods: equipment weapons, attack (2) define weapon class weapon variables: weapon_type (weapon type), lethal (lethal) (3) Attacking the enemy creates players and enemy objects and initializes the attributes. After creating the weapon object, the player object is equipped with weapons. The player calls the attack method to attack. The
correct answer:

class Player():

    def __init__(self, name):

        self.name = name

        self.blood = 100

        self.weapon = None

        print("创建名为%s的玩家对象" % (self.name))

    def armed(self, weapon):

        self.weapon = weapon

        print("%s装备了杀伤力为%d点的%s" % (self.name, weapon.lethal, weapon.weapon_type))

    def attack(self,target):

        target.blood -= self.weapon.lethal

        print("%s使用%s攻击%s,造成%d点伤害" % (self.name, self.weapon.weapon_type, target.name, self.weapon.lethal ))

        print("%s还剩%d点血" % (target.name, target.blood))

class Weapon():

    def __init__(self, weapon_type, lethal):

        self.lethal = lethal

        self.weapon_type = weapon_type

 

player = Player("大漠雄鹰")

enemy = Player("大反派")

player.armed(Weapon("平底锅", 5))

player.attack(enemy)

player.attack(enemy)

player.attack(enemy)

4 Define a student class (Student)

, Requirements: (1) Initialize data member data member ( Sno, Sname, Sage); (2) Define data member (Sno, Sname, Sage) through attribute decorator;
(3) Define special method __str
(self), the The method returns: Such a string "My name is Zhang San, student number is 1101, age is 33, is a student", where Zhang San, 1101, 33, according to user input to display. ";
(4) the definition of a graduate class through inheritance (Gra_student), and increase the data members of the research ( Research,)
(5) in Gra_student class, define special methods __str
(Self), the method returns: My name is Four, Student ID is 1102, age is 35, is a graduate student, the research direction is complex network;
(6) call the student class s = Student ('zs', '1101', 23), and the special method __str __ ( self), modify the student's age to 33, call __str __ (self) again; (7) call the graduate class ga = Gra_student ('李四', '1102', 35, 'complex network'), call __str __ (self) . The
correct answer:

class Student(object):

    def __init__(self, Sname, Sno, Sage):

        self.Sno = Sno

        self.Sname = Sname

        self.Sage = Sage

    @property

    def Sno(self):

        return self._Sno

    @Sno.setter

    def Sno(self, sno):

        self._Sno = sno

    @property

    def Sname(self):

        return self._Sname

    @Sname.setter

    def Sname(self, sname):

        self._Sname = sname

    @property

    def Sage(self):

        return self._Sage

    @Sage.setter

    def Sage(self, sage):

        self._Sage = sage

    def __str__(self):

        return '我叫%s,学号是%s,年龄为%s,是一名学生' % (str(self.Sname), str(self.Sno), str(self.Sage))

    def run(self):

        return '我叫%s,学号是%s,年龄为%s,是一名学生' % (str(self.Sname), str(self.Sno), str(self.Sage))

 

class Gra_student(Student):

    def __init__(self, Sno, Sname, Sage, Skey):

        super().__init__(Sno, Sname, Sage)

        self.Skey = Skey

    def __str__(self):

        return '我叫%s,学号是%s,年龄为%s,是一名研究生' % (str(self.Sname), str(self.Sno), str(self.Sage))

5 Define a three-dimensional vector class and define corresponding special methods to implement addition and subtraction operations between two objects of this type (requires support for operators +,-), and implement multiplication and division operations of objects of this type and scalars (requires support Operators *, /), and the calculation of vector length (requires the use of attributes).

correct answer:

class Vector3:

#构造方法,初始化,定义向量坐标

    def __init__(self, x, y, z):

        self.__x = x

        self.__y = y

        self.__z = z

#与两一个向量相加,对应分量相加,返回新向量

    def __add__(self, anotherPoint):

        x = self.__x + anotherPoint.__x

        y = self.__y + anotherPoint.__y

        z = self.__z + anotherPoint.__z

        return Vector3(x, y, z)

#减去另一个向量,对应分量相减,返回新向量

    def __sub__(self, anotherPoint):

        x = self.__x - anotherPoint.__x

        y = self.__y - anotherPoint.__y

        z = self.__z - anotherPoint.__z

        return Vector3(x, y, z)

#向量与一个数字相乘,各分量乘以同一个数字,返回新向量

    def __mul__(self, n):

        x, y, z = self.__x*n, self.__y*n, self.__z*n

        return Vector3(x, y, z)

#向量除以一个数字,各分量除以同一个数字,返回新向量

    def __truediv__(self, n):

        x, y, z = self.__x/n, self.__y/n, self.__z/n

        return Vector3(x, y, z)

#查看向量长度,所有分量平方和的平方根

    @property

    def length(self):

        return (self.__x**2 + self.__y**2 + self.__z**2)**0.5

    def __str__(self):

        return 'Vector3({},{},{})'.format(self.__x,self.__y,self.__z)

#用法演示

v1 = Vector3(3, 4, 5)

v2 = Vector3(5, 6, 7)

print(v1+v2)

print(v1-v2)

print(v1*3)

print(v2/2)

print(v1.length)
Published 27 original articles · praised 3 · visits 1414

Guess you like

Origin blog.csdn.net/weixin_41860600/article/details/105637145