Python教程

Python---day8作业

本文主要是介绍Python---day8作业,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.定义一个类(不限定定义哪个类):
要求: a.需要有一个类变量
b.需要有>=2个的对象变量
c.定义一个方法:打印类变量和对象变量
d.使用print打印对象->输出为This is a object
e.实例化两个对象:且两个对象相加等于2
f.为对象添加一个临时变量temp_var

class Person:
    type = "Person Class"

    def __init__(self, name, age):
        self.name = name
        self.age = age
    def print_info(self):
        print("类变量:", Person.type)
        print("对象变量:", self.name, self.age)
    def __str__(self):
        return "This is a object"
    def __add__(self, other):
        return 2


zhangsan = Person("zhangsan", 18)
print(zhangsan)
lisi = Person("lisi", 20)
print(zhangsan + lisi)
zhangsan.print_info()
zhangsan.type = "temp_var"
print(zhangsan.type)
This is a object
2
类变量: Person Class
对象变量: zhangsan 18
temp_var

2.super的使用:
定义一个类A, 里面又一个方法print_info
定义一个类B, 里边有一个方法print_info和一个方法say_something
定义一个类C, 里边有一个方法say_something
定义一个类D, 里边有一个方法print_info和一个方法say_something
定义一个类E,继承类A, 类B, 类C,类D

class A:
    def print_info(self):
        print("This is A")
  
class B:
    def say_somthing(self):
        print("B says something")
    def print_info(self):
        print("This is B")
  
class C:
    def say_somthing(self):
        print("C says something")
  
class D:
    def say_somthing(self):
        print("D says something")
    def print_info(self):
        print("This is D")
   
class E(A, B, C, D):
   

实例化类E的对象
执行print_info和say_something方法

obj = E()
obj.print_info()
obj.say_somthing()

利用super,让执行print_info时调用B中print_info

class E(A, B, C, D):
    def print_info(self):
        super(A, self).print_info()
   
obj = E()
obj.print_info()
obj.say_somthing()
This is B
B says something

利用super, 让执行say_something时调用C中say_something

class E(A, B, C, D):
    def say_somthing(self):
        super(B, self).say_somthing()
        
obj = E()
obj.print_info()
obj.say_somthing()
C says something

利用super, 让执行print_info和say_something时调用
D中print_info和say_something

class E(A, B, C, D):
    def print_info(self):
        super(C, self).print_info()
    def say_somthing(self):
        super(C, self).say_somthing()

obj = E()
obj.print_info()
obj.say_somthing()
This is D
D says something
print(E.__mro__)
(<class '__main__.E'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>, <class 'object'>)
这篇关于Python---day8作业的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!