Python practice - Dongdong instructor Python advanced tutorial

2.2 please practice defining an animal class, create two instances dog, cat, print the instance, and then compare whether the two instances are equal
class Animal(object):
    pass
dog = Animal()
cat = Animal()
print(cat)
print(dog==cat)
<__main__.Animal object at 0x00000189935BD280>
False
2.3 please define an animal class and create two instances dog and cat, with different names and ages.
class Animal(object):
    pass
dog = Animal()
cat = Animal()
dog.name = 'xiaohuang'
dog.age = 1
cat.name = 'xiaohua'
cat.age = 2
2.4 please define an animal class, abstract the two attributes of name and age, and instantiate two instances dog and cat.
class Animal(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
dog = Animal('xiaohuang',3)
cat = Animal('xiaohua',4)
print(dog.name,dog.age)
print(cat.name,cat.age)
xiaohuang 3
xiaohua 4
2.5 Please add a class attribute count to the Animal class. For each instance created, the count attribute will be increased by 1. In this way, you can count how many instances of Animal have been created.
class Animal(object):
    location = 'China'
    count = 0
    def __init__(self,name,age):
        self.name = name
        self.age = age
        Animal.count += 1

dog = Animal('xiaohuang',4)
cat = Animal('xiaohua',3)
pig = Animal('xiaozhu',6)
print(dog.name,dog.age)
print(cat.name,cat.age)
print(pig.name,pig.age)
print(Animal.count)
xiaohuang 4
xiaohua 3
xiaozhu 6
3
2.6 please change the Animal class attribute count in the previous section to__ Count, and then try whether the property can be accessed from the instance and class.
class Animal(object):

    __count = 0

    def __init__(self,name):

        Animal.__count = Animal.__count + 1

        self.name = name

        print('inside:{}'.format(Animal.__count))

p1 = Animal('Cat')

p2 = Animal('Dog')
inside:1
 inside:2
2.7 please give the__ init__ Method, and bind age to__ On the age attribute, see if it can be accessed externally. (obviously unable to access, the program reports an error)
class Animal(object):
    def __init__(self,name,age):
        self.name = name
        self.__age = age

dog = Animal('xiaohuang',12)
print(dog.name,dog.__age)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

Input In [72], in <cell line: 7>()
      4         self.__age = age
      6 dog = Animal('xiaohuang',12)
----> 7 print(dog.name,dog.__age)


AttributeError: 'Animal' object has no attribute '__age'
2.8 define age, name and localization of the Animal class as private properties, and define corresponding methods to modify and obtain their values.
class Animal(object):
    def __init__(self,name,age,location):
        self.__name = name
        self.__age = age
        self.__location = location
        
    def set_name(self,name):
        self._name = name
        
    def get_name(self):
        return self.__name
        
    def set_age(self,age):
        self._age = age
        
    def get_age(self):
        return self._age
        
    def set_location(self,location):
        self_location = location
        
    def get_location(self):
        return self._location
        
dog = Animal('xiaohuang',2,'GuangDong')
print(dog.get_name())
dog.set_age(5)
print(dog.get_age())
xiaohuang
5
2.9 if the class attribute count is changed to a private attribute__ Count, the external cannot get__ Count, but it can be obtained through a class method. Please write a class method to obtain__ Count value.
class Animal(object):
    __location = 'Asia'
    __count = 0
    def __init__(self,name,age):
        self.name = name
        self.age = age
        Animal.__count += 1
        
    @classmethod
    def set_location(cls,location):
        cls.__location = location
    
    @classmethod
    def get_location(cls):
        return cls.__location
    
    @classmethod
    def get_count(cls):
        return cls.__count

dog = Animal('xiaohua',4)
        
print(Animal.get_location())
Animal.set_location('China')
print(Animal.get_location())

print(Animal.get_count())
Asia
China
1
3.2 please refer to the Student class and write the Teacher class. The Teacher has the attribute of teaching a certain subject.
class Person(object):
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender

class Student(Person):
    def __init__(self,name,gender,score):
        super(Student,self).__init__(name,gender)
        self.score = score

student = Student('julia','girl',18)
print(student.name)
print(student.gender)
print(student.score)

class Teacher(Person):
    def __init__(self,name,gender,course):
        super(Teacher,self).__init__(name,gender)
        self.course = course

teacher = Teacher('Jue','boy','MATH')
print(teacher.name)
print(teacher.gender)
print(teacher.course)
julia
girl
18
Jue
boy
MATH
3.3 please consider whether t is the type of Person, Student, Teacher and object according to the type conversion of inheritance chain, and use isinstance() to verify your answer.
class Person(object):
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender

class Student(Person):
    def __init__(self,name,gender,score):
        super(Student,self).__init__(name,gender)
        self.score = score
        
class Teacher(Person):
    def __init__(self,name,gender,course):
        super(Teacher,self).__init__(name,gender)
        self.course = course

p = Person('Bob','male')
s = Student('Julie','female',56)
t = Teacher('Tim','male','English')
print(isinstance(t,Person))
print(isinstance(t,Student))
print(isinstance(t,Teacher))
print(isinstance(t,object))
True
False
True
True
3.4 the known classes Student and Teacher inherit the Person class, and the skill classes basketball mixin and football mixin inherit the SkillMixin class. Please define "students who can play basketball" and "teachers who can play football" through multiple inheritance.
class Person(object):
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender


class SkillMixin(object):
    def __init__(self,skill):
        self.skill = skill
    def say(self):
        print("Skills are:%s"%(self.skill))

class BasketballMixin(SkillMixin):
    def __init__(self,skill):
        super(BasketballMixin,self).__init__(skill)

class FootballMixin(SkillMixin):
    def __init__(self,skill):
        super(FootballMixin,self).__init__(skill)

class Student(Person,BasketballMixin):
    def __init__(self,name,gender,score,skill):
        super(Student,self).__init__(name,gender)
        BasketballMixin.__init__(self, skill)
        self.score = score
    def say(self):
        print("Student Name:%s,Gender%s,The test score is:%d, like%s" %(self.name, self.gender, self.score, self.skill))
        
class Teacher(Person,FootballMixin):
    def __init__(self, name, gender, subject,skill):
        super(Teacher, self).__init__(name, gender)
        FootballMixin.__init__(self,skill)
        self.subject = subject
        
    def say(self):
        print("Teacher's name%s,Gender%s,Teaching subjects:%s, like%s" %(self.name, self.gender, self.subject,self.skill))
        



s = Student('Xiaoming','male',45,'Basketball')
s.say()
t = Teacher('Xiao Wang','male','MATH','Football')
t.say()
The student's name is Xiaoming, gender is male, the test score is 45, I like it Basketball
 The teacher's name is Xiao Wang, gender is male, teaching subject is MATH, like Football
3.5 for the definition of the Person class, you want to provide any additional keyword parameters in addition to name and gender, and bind them to the instance. Please modify the__ init__ () define and complete the function.
class Person(object):
    def __init__(self, name, gender,**kw):
        self.name = name
        self.gender = gender
        for k,v in kw.items():
            setattr(self,k,v)
p = Person('Alice','girl',age=13,course='Python')
print(p.age)
print(p.course)
13
Python
4.2 please define the Student class__ str__ And__ repr__ Method to print 'Student: name, gender, score'.
class Person(object):
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender

class Student(Person):
    def __init__(self,name,gender,score):
        super(Student,self).__init__(name,gender)
        self.score = score
    
    def __str__(self):
        return 'Student:{},{},{}'.format(self.name,self.gender,self.score)
    
    def __repr__(self):
        return 'STUDENT:{},{},{}'.format(self.name,self.gender,self.score)

student = Student('xiaohua','boy',78)
print(student)
print('%r'%student)
print(str(student))
print(repr(student))
Student:xiaohua,boy,78
STUDENT:xiaohua,boy,78
Student:xiaohua,boy,78
STUDENT:xiaohua,boy,78
4.3 Fibonacci sequence is composed of 0, 1, 1, 2, 3, 5, 8. Please write a Fib class. Fib(10) represents the first 10 elements of the sequence, print Fib(10) can print the first 10 elements of the sequence, and len(Fib(10)) can correctly return the number 10 of the sequence.
class Fib(object):
    def __init__(self,num):
        self.Lis = []
        self.num = num
        a = 0
        b = 1
        for i in range(num):
            self.Lis.append(a)
            a = b
            b = a+b
    
    def __len__(self):
        return self.num
        
    def __str__(self):
        return str(self.Lis)
        
f = Fib(10)
print(f)
print(len(f))
[0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
10
4.4 although the Rational class can do addition, it cannot do subtraction, multiplication and division. Please continue to improve the Rational class to realize four operations.
class Rational(object):
    def __init__(self,p,q):
        self.p = p
        self.q = q
        
    def __add__(self,r):
        return Rational(self.p*r.q+self.q*r.p,self.q*r.q)
    
    def __sub__(self,r):
        return Rational(self.p*r.q-self.q*r.p,self.q*r.q)
    
    def __mul__(self,r):
        return Rational(self.p*r.p,self.q*r.q)
        
    def __truediv__(self,r):

        return Rational(self.p*r.q,self.q*r.p)
    
    def __str__(self):
        return '{}/{}'.format(self.p,self.q)

r1 = Rational(1,2)
r2 = Rational(2,3)
print(r1+r2)
print(r1-r2)
print(r1*r2)
print(r1/r2)
7/6
-1/6
2/6
3/4
4.5 assume that the Person class passes__ slots__ Name and gender are defined. Please pass__ slots__ Continue to add the definition of score so that the Student class can implement the three attributes of name, gender and score.
class Person(object):
    __slots__ = ('name','gender')
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender
class Student(Person):
    __slots__ = ('name','gender','score')
    def __init__(self,name,gender,score):
        super(Student,self).__init__(name,gender)
        self.score = score
st = Student('xiaohua','boy',67)
st.gender = 'girl'
st.score = 90
print(st)
<__main__.Student object at 0x0000018993F449A0>
4.6 please implement the Fibonacci sequence class Fib described above and add__ call__ Method, making the calling method as follows simple.

f = Fib()
print f(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

class Fib(object):
    def __init__(self):
        pass
        
    
    def __call__(self,num):
        self.Lis = []
        a = 0
        b = 1
        for i in range(num):
            self.Lis.append(a)
            a = b
            b = a+b
        return self.Lis
        
f = Fib()
print(f(10))
[0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
5.2 define a common module, common.py, in common Py, including the public function say_hello(name), which takes a parameter and outputs the result of Hello.
def say_hello(name):
    print('Hello{}'.format(name))
say_hello("xiaohua")
Helloxiaohua
The 5.3 math module also provides many mathematical calculation functions, such as sine sin() function and cosine cos() function. Please use two import methods to use these two functions.
import math
print(math.sin(0))
print(math.cos(0))

from math import sin,cos
print(sin(90))
print(cos(90))
0.0
1.0
0.8939966636005579
-0.4480736161291701
5.4 Python's sys.path returns a path list, so you can operate the elements in the list. Please add the path '... /' through sys.path to import the packages of the parent directory of the current directory at runtime.
import sys
print(sys.path)
sys.path.append('../')
print(dir(sys.path))
['C:\\Users\\Administrator\\JUPYTERLAB', 'D:\\Anaconda3\\python39.zip', 'D:\\Anaconda3\\DLLs', 'D:\\Anaconda3\\lib', 'D:\\Anaconda3', '', 'D:\\Anaconda3\\lib\\site-packages', 'D:\\Anaconda3\\lib\\site-packages\\win32', 'D:\\Anaconda3\\lib\\site-packages\\win32\\lib', 'D:\\Anaconda3\\lib\\site-packages\\Pythonwin', '../']
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
5.5 requests is a good HTTP module. Please install this module through pip.

pip install request

6.1 the eval() function can convert a string into an equivalent result, such as Eval ('1 + 1 '), and the result is 2. Please use Eval to implement a simple calculator that can input expressions and print the calculation results.
while True:
    s = input('>>> ')
    if s == 'break':
        break
    result = eval(s)
    print(result)
>>> 



Traceback (most recent call last):


  File D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3369 in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)


  Input In [87] in <cell line: 2>
    result = eval(s)


  File <string>
    
    ^
SyntaxError: unexpected EOF while parsing
6.2 please try to open a text file with the specified absolute path in read-only mode and close it correctly.
f = open('test.txt','r')
f.close()
6.3 please try to open a binary file with specified absolute path in read-only mode and close it correctly.
f = open('test.txt','rb')
f.close()
6.4 implement a read.py file and print the contents of the read.py file.
f = open('read.py')
content = f.readlines()
print(content)
['read me']
6.5 test Txt file, including the following contents: Hello world, hello python, hello imooc please read the above contents from the test.txt file, invert each line of string, and write it to the test1.txt file
f = open('test.txt', 'r')
lines = f.readlines()
f1 = open('test1.txt', 'w')
for line in lines:
    line = line[::-1]
    f1.write(line)

f1.close()
f.close()
6.6 hypothesis test Txt file has the following contents: Hello World Hello Python Hello Imooc please write a duplicate of the contents of the file and append it to the end of the file
with open('test.txt','a+') as f:
    lines = f.readlines()
    f.seek(2)
    f.writelines(lines)
8.2 use the add(x, y, f) function defined above to calculate the root number x + the root number y
import math
def add(x,y,f):
    return f(x)+f(y)
an = add(5,8,math.sqrt)
print(an)
5.06449510224598
8.3 assuming that the English names entered by the user are not standardized, and do not follow the rules of uppercase for the first letter and lowercase for the subsequent letters, please use the map() function to change a list (containing several nonstandard English names) into a list containing standard English names:

Input: [alice ',' BOB ',' CanDY ']
Output: ['Alice', 'Bob', 'Candy']

def f(s):
    return s[0].upper()+s[1:].lower()
    
for item in map(f,['alice','BoB','canDy']):
    print(item)
Alice
Bob
Candy
8.4 Python has a built-in summation function sum(), but there is no function for quadrature. Please use recurse() to quadrature

Input: [1, 3, 5, 7, 9]
Output: result of 13579

import functools
def f(x,y):
    return x*y

print(reduce(f,[1,3,5,7,9]))
945
8.5 please use filter() to filter out the number whose square root is an integer from 1 to 100, that is, the result should be: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100.
import math
def f(x):
    r = int(math.sqrt(x))
    return r*r == x
for item in filter(f,range(1,101)):
    print(item)
1
4
9
16
25
36
49
64
81
100
8.6 when sorting strings, sometimes it is more customary to ignore case sorting. Please use the sorted() high-order function to implement the algorithm that ignores case sorting.

Input: [bob ',' about ',' Zoo ',' Credit ']
Output: [about ',' bob ',' Credit ',' Zoo ']

def k(item):
    return item.lower()

print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=k))
['about', 'bob', 'Credit', 'Zoo']
8.7 please write a function calc_prod(list_), It receives a list and returns a function, which can calculate the product of parameters.
from functools import reduce

def calc_prod(list_):
    def lazy_prod():
        def f(x, y):
            return x * y
        return reduce(f, list_, 1)
    return lazy_prod

f = calc_prod([1, 2, 3, 4])
f()
24
8.8 when sorting strings, sometimes it is more customary to ignore case sorting. Please use the sorted() high-order function and lambda anonymous function to implement the algorithm that ignores case sorting.

Input: [bob ',' about ',' Zoo ',' Credit ']
Output: [about ',' bob ',' Credit ',' Zoo ']

sorted(['bob', 'about', 'Zoo', 'Credit'], key=lambda item: item.lower())
['about', 'bob', 'Credit', 'Zoo']
8.9 please use functools Partial turns this complex call into a simple function: sorted_ignore_case([‘bob’, ‘about’, ‘Zoo’, ‘Credit’])
import functools
sorted_ignore_case = functools.partial(sorted, key=lambda item: item.lower())
sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
['about', 'bob', 'Credit', 'Zoo']

Tags: Python Django programming language

Posted by filippe on Sun, 21 Aug 2022 01:19:55 +0930