Name: Ah Yue's Little Dongdong
Learning: python. c
Homepage: Gone
Today, Ayue will take you to see more detailed python exercises
Table of contents
2.1 Examples of static methods:
2.2 Examples of class methods:
2.3 Examples of attribute methods:
3. a=1, b=2, do not exchange the values of a and b without intermediate variables
6. Please write the print result:
7. Tell me about the problem with the following code snippet
1. In python, what is the difference between list, tuple, dict, and set, and what kind of scenarios are they mainly used in?
definition:
list: linked list, ordered items, search by index, use square brackets "[]";
tuple: tuple, tuple is a collection of various objects together, cannot be modified, searched by index, use brackets "()";
dict: dictionary, a dictionary is a combination of a key (key) and a value (value), search through the key (key), there is no order, use braces "{}";
set: collection, unordered, element appears only once, automatic deduplication, use "set([])";
Application scenario:
list, simple data collection, can use index;
tuple, use some data as a whole and cannot be modified;
dict, data associated with keys and values;
set, the data only appears once, only care about whether the data appears, not its position;
mylist = [1, 2, 3, 4, 'Oh'] mytuple = (1, 2, 'Hello', (4, 5)) mydict = {'Wang' : 1, 'Hu' : 2, 'Liu' : 4} myset = set(['Wang', 'Hu', 'Liu', 4, 'Wang'])
2. What is the difference between static function, class function, member function and property function?
definition:
Static function (@staticmethod): That is, a static method, which mainly deals with the logical association with this class, and it cannot access instance variables or class variables.
Class function (@classmethod): That is, a class method, which can only access class variables and cannot access instance variables. Class methods are implemented through the @classmethod decorator.
Member function: The method of the instance can only be called through the instance. If it needs to be called through the class name, it should be declared as a class method.
Property function: Turn a method into a static property through @property.
concrete application:
The date method can be instantiated (__init__) for data output, and the parameter self is passed in;
Data conversion can be performed through the method of the class (@classmethod), and the parameter cls is passed in;
Data validation can be done through static methods (@staticmethod);
2.1 Examples of static methods:
class People(object): Name="class variable name" def __init__(self,name): self.name=name @staticmethod def run(self): print("%s is a staticmethod"%self.name) @staticmethod def talk(): print("who is talking") p1=People("Wang Wenhui") p1.run() # Solution: Actively pass the instance itself to the run method when calling. p1.run(p1) # Solution: Remove the self parameter in the run method, but this also means that other variables in the instance cannot be called through self. p1.talk()
2.2 Examples of class methods:
class Cat(object): name="i is class variable" def __init__(self,name): self.name=name @classmethod def sleep(self): print("%s is a classname"%self.name) c1=Cat("big cat") c1.sleep()
2.3 Examples of attribute methods:
# The definition of a property method is to turn a method into a static property through @property. class Cat(object): def __init__(self,name): self.name=name @property def talk(self): print("%s is a property method"%self.name) c1=Cat("big cat") # There will be an error in the call, because talk has become a static attribute at this time, not a method, and no brackets are needed. c1.talk() c1.talk # Function: Change the status of the attribute as needed, such as obtaining the current status of the flight, arriving, delayed or flying away.
3. a=1, b=2, do not exchange the values of a and b without intermediate variables
Solution: Three forms: direct exchange, addition or XOR
Example:
a=1 b=2 a,b=b,a print(a,b) a=a+b b=a-b a=a-b print(a,b) a=a^b b=a^b a=a^b print(a,b)
4. Write a function, input a string, and return the results in reverse order: For example: string_reverse('abcdef'), return: 'fedcba' (please use multiple methods to implement, and compare the implementation methods)
class Solution(object): def __init__(self,s): self.s=s def reverseString(self): list_string=list(self.s) list_string.reverse() str2="".join(list_string) return str2 str1="hello" c1=Solution(str1) print("\"%s\""%(c1.reverseString()))
5. Please use your own algorithm to merge the following two list s in ascending order and remove duplicate elements:
list1 = [2, 3, 8, 4, 9, 5, 6]
list2 = [5, 6, 10, 17, 11, 2]
Answer: First convert it into a set to automatically deduplicate, and then convert it into a list.
list1=[2,7,4,15,10] list2=[6,1,9,10,7] list3=list(set(list1+list2))
6. Please write the print result:
x = [0, 1]
i = 0
i, x[i] = 1, 2
print(x)
Print result: [0, 2], python can use continuous assignment, from left to right.
g = lambda x, y=2, z : x + y**z
g(1, z=10) = ?
Print result: Abnormal, there can be default parameters at the end of the formal parameter list, and z needs to provide default parameters.
7. Tell me about the problem with the following code snippet
from amodule import * # amodule is an exist module class dummyclass(object): def __init__(self): self.is_d = True pass class childdummyclass(dummyclass): def __init__(self, isman): self.isman = isman @classmethod def can_speak(self): return True @property def man(self): return self.isman if __name__ == "__main__": object = new childdummyclass(True) print object.can_speak() print object.man() print object.is_d
answer:
1. Warning: object is a reserved keyword in python and should not be redefined.
2. A class method is a method owned by a class, and the parameter passed in should be cls, not self.
3. Error: Python does not need the new keyword to instantiate objects.
4. Error: @property means a property, not a method, so there is no need to add brackets "()", just call object.man directly.
5. Error: If you want to rewrite the construction method of the base class, you need to inherit the construction method of the base class and rewrite it.
6. Extra: Class names should be capitalized as much as possible.
class Dummyclass(object): def __init__(self): self.is_d=True pass class ChildDummyclass(Dummyclass): def __init__(self,isman): super(ChildDummyclass, self).__init__() self.isman=isman @classmethod def can_speak(cls): return True @property def man(self): return self.isman if __name__ == '__main__': o=ChildDummyclass(True) print(o.can_speak()) print(o.man) print(o.is_d)
8. Introduce the exception handling mechanism of python and the experience in the development process
Answer: Python's exception handling mechanism:
try: try to throw an exception;
raise: raise an exception;
except: handle exception;
finally: things that need to be done whether an exception occurs;
To create a new exception type, you need to inherit the Exception class, and you can define the attributes of the class to facilitate exception handling;
# Actively trigger exceptions try: raise Exception("An error occurred") except Exception as e: print(e) # custom exception class wangwenhuiwrong(object): def __init__(self,name): self.name=name def __str__(self): return self.message try: raise wangwenhuiwrong("An error occurred") except Exception as e: print(e)
hey hey
write at the end
In fact, there is nothing wrong with it. It is just that school is about to start, and I haven’t written my homework. Who can help me write some, hahahahahaha, I wish you all a happy broken five