Python Basics Lesson Four

Source: Internet
Author: User

GitHub Blog Portal
CSDN Blog Portal

Object oriented

For beginners This piece is more difficult, it is recommended that you quickly read the concept, and then whether it will not first copy a few questions (note: Must hand dozen) Recommended 3 simple brush three times a total of nine times after the concept easy to understand some.
To be more advanced, object-oriented is to rewrite the pointer of memory, but we don't talk about it so much today. Let's take it easy. Look after the novice.

class: used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
( Self-visualizing understanding (helping beginners to understand): a person carrying an empty bag, nothing, we can compare this empty package to: class .)

Class variables: class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are not typically used as instance variables.
( Self-visualizing understanding (helping beginners Understand): a person carrying a bag with a lot of properties, such as the capacity of the bag, all the things put into the bag can be used in this container. Each one of these will have a reduced capacity, and this capacity will increase with each thing. We call this package capacity/ The property of the package is this empty package/class: class variable .)

method: a function defined in a class.
( self-visualizing understanding): If the empty bag has some tools such as a hammer, a veil, a cell phone, a purse, and so on, the hammer can be used to knock things, the veil can be used to wash the sweat, etc. then we call these tools: methods .)

instantiation: Creates an instance of a class, the concrete object of the class.
( Self-visualizing understanding (helping beginners to understand): a person carrying a bag, the tools/methods in the bag need to be used to make sense. This person is equivalent to the use of the tool in the bag. This person is equivalent to instantiating /class instantiation The only thing that is not the same as usual is that each instantiation of an object is one more person using this package is to copy the package and we can use the same tool together.

instance variable: A variable defined in a method that acts only on the class of the current instance.
( Self-visualizing understanding (helping beginners to understand): define variables within each method. Each time a variable is instantiated, each person uses a tool/method differently, that is, the tool is used in a specific variable/ instance variable that is currently used by this person.

inheritance: A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of type dog is derived from the animal class, which is the impersonation "is a (is-a)" Relationship (dog is a animal)
( self-visualizing understanding): A person carries a bag with a lot of tools, and when he gives it to his son, his son can either use the tools in the bag or add some new tools himself and use this to call it: inheritance .

method Overrides: if the method inherited from the parent class does not meet the requirements of the subclass, it can be overridden, which is called the override of the method, also known as the override of the method.
( self-visualizing understanding): When the son inherited the package from his father, he felt that the hammer was not very good, and decided to replace it with a hammer head or a hammer. This is called a rewrite of the method .

data members: class variables or instance variables are used to manipulate the data related to the class and its instance objects.
(Self-understanding, this piece is used less.)

object: An instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.
(Self-understanding, this piece is used less.)

Define the format of a class
class 类名:                        # 创建一个类必写    类变量名 = 类变量的值            # 非必需    def 方法名1:                   # 基本必需 不然创建这个类就没有意义了        实例变量名 = 实例变量的值    # 非必需        方法块    .    .    .    def 方法名N:        方法块# 实例化这个类变量名People = 类名()    # 这样就实例化了一个对象 相当于我们之前说的创建了一个人使用这个包.变量名People.方法名1()   # 这样就可以调用 实例化对象的方法了.

Initialization mode

class Fun:    # __init__这个方法会在你创建实例的时候自动执行    def __init__(self,name): # 新手可能会对self这个词有所疑惑,我只能建议你,每个方法都要写self,并且是写在第一个参数位置的,新手直接无视 也就是当作没有self这个词就可以了.        print(‘初始化这个实例对象的人是:{}‘.format(name))# 我们实例化一下这个类fun = Fun(‘Mrzhang‘)# 然后就会自动打印初始化这个实例对象的人是:Mrzhang    #就将Mrzhang传给这个方法了.

The inherited format

class Animal:   # 创建了一个动物animal类 动物都可以吃    def eat(self):        print(‘Animal is eat‘)class Dog(Animal):    # 创建了一个dog类 继承animal    def run(self):        print(‘Dog is run‘) # 也就是说 dog 类既有 run方法 也有 eat吃 方法dog = Dog()dog.eat()dog.run()# 输出Animal is eatDog is run

The basic said so much back to the three I learned when the practice of the topic practiced three times. Whether you understand it or not, you can read it three times before you look back and see the concept clear.

First question
# coding=utf-8"""一:定义一个学生类。有下面的类属性:1 姓名2 年龄3 成绩(语文,数学,英语)[每课成绩的类型为整数]类方法:1 获取学生的姓名:get_name() 返回类型:str2 获取学生的年龄:get_age() 返回类型:int3 返回3门科目中最高的分数。get_course() 返回类型:int写好类以后,可以定义2个同学测试下:zm = Student(‘zhangming‘,20,[69,88,100])返回结果:zhangming20100"""class Student(object):    def __init__(self, name, age, scores):        self.name = name        self.age = age        self.scores = scores    def get_name(self):        return self.name    def get_age(self):        return self.age    def get_course(self):        return max(self.scores)zm = Student(‘zhangming‘, 20, [69, 88, 100])print(zm.get_name())print(zm.get_age())print(zm.get_course())# 输出下面这些数值就是没有问题了zhangming20100
Second question
"" "Two: Define a dictionary class: Dictclass. Complete the following functions: Dict = Dictclass ({You need to manipulate the Dictionary object}) 1 Delete a keydel_dict (key) 2 to determine if a key is in the dictionary, if the value corresponding to the return key, does not exist then return "not Found" get_dict (key) 3 returns the list of key components: return type, (list) Get_key () 4 merged dictionary, and returns a list of values consisting of the merged dictionary. return type: (list) update_dict ({Dictionary to merge}) "" "Class Dictclass (object): Def __init__ (self, dict): self.dict = Dict def ge T_dict (self, key): If key in Self.dict:return Self.dict[key] return ' not found ' def del_dict ( Self, key): If key is Self.dict:self.dict.pop (key) Else:return ' No that key ' Def         Get_key (self): return Self.dict.keys () def updata_dict (self, dict2): Self.dict = Dict (self.dict, **dict2) Return self.dict.values () A = Dictclass ({' A ': 1, ' B ': 2}) Print (A.get_dict (' C ')) (A.del_dict (' C ')) print (A.get_ke Y ()) print (A.updata_dict ({' C ': 3, ' d ': 4}) # about deleting elements in the dictionary # Pop deletes and returns the corresponding value value b = {' A ': 1, ' B ': 2}print (B.pop (' B ')) print (b) # D El Void does not return a value C = {' A ': 1, ' B ': 2}del c[' a ']print (C) # del dict Delete dictionary, does not exist thisDictionary # dict.clear () Delete all the elements in the dictionary but the dictionary still exists just no element D = {' A ': 1, ' B ': 2, ' C ': 3}d.clear () # about Merge Dictionary a = {' A ': 1, ' B ': 2, ' C ': 3}b = {' D ': 4 , ' E ': 5, ' f ': 6}c = a.update (B) D = Dict (A, **b) # This merging method is much faster than the previous one. For duplicate key,b overwrites a# output The following values are no problem: not Foundno that Keydict_keys ([' A ', ' B ']) dict_values ([1, 2, 3, 4]) 2{' a ': 1}{' B ': 2}
Third question
"" "Defines the action class for a list: Listinfo includes methods: 1 list elements added: Add_key (keyname) [KeyName: String or integer type]2 list element value: Get_key (num) [num: integer type]3 List merge: Update_list [list]: List type]4 Delete and return the last element: Del_key () List_info = Listinfo ([44,222,111,333,454, ' SSS ', ' 333 ']) ""        "Class Listinfo (object): Def __init__ (self, list_val): self.varlist = List_val def add_key (self, key_name):        If Isinstance (Key_name, (str, int)): Self.varlist.append (key_name) return self.varlist            Else:return ' ERROR ' def get_key (self, num): If num >= 0 and Num < len (self.varlist): return Self.varlist[num] Else:return ' ERROR ' def update_list (self, list_et): SELF.VARLIST.E Xtend (List_et) return self.varlist def del_key (self): If Len (self.varlist) >= 0:return sel F.varlist.pop ( -1) Else:return ' error ' List_info = Listinfo ([, 222, 111, 333, 454, ' sss ', ' 333 ']) print ( List_info.add_key (' 1111 ')) print (List_infO.get_key (4)) print (List_info.update_list ([' 1 ', ' 2 ', ' 3 ')) print (List_info.del_key ()) # There is no problem with outputting the following data: [44, 222, 111, 333 , 454, ' sss ', ' 333 ', ' 1111 ']454[44, 222, 111, 333, 454, ' sss ', ' 333 ', ' 1111 ', ' 1 ', ' 2 ', ' 3 ']3

If you have finished three times these three questions I believe that we have a certain understanding of the basic object-oriented operation. We recommend that you look back at the concept of object-oriented. The rest of the small problems in the actual combat to solve it.

Python Basics Lesson Four

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.