Python OOP learning notes-1

1. python standard library: python 3.9.4

(1)format():

format(value[, format_spec])

Convert # value # to # format_ "Formatted" representation of spec # control. format_ The interpretation of spec , depends on the type of , value , argument, but most built-in types use standard formatting syntax: Format specification Mini language.

Default format_spec is an empty string, which is usually the same as calling str(value) The results are the same.

Calling _format(value, format_spec) will be converted to _type (value)__ format__ (value, format_spec), so in the instance dictionary __format__() Method will not be called. If found object There is this method, but , format_spec , is not empty, format_ If the spec or return value is not a string, it will be triggered TypeError Abnormal.

(2)hash():

hash(object)

Returns the hash value of the object, if any. The hash value is an integer. They are used to quickly compare dictionary keys when looking up elements in the dictionary. Numeric variables of the same size have the same hash value (even if they are of different types, such as 1 and 1.0).

Note: if the object implements its own __hash__() Method, please note, hash() Truncate the return value according to the word length of the machine. See also __hash__().

2 OOP learning

2.1 # class and object

1. Class: the abstraction of a class of things in the real world

#Teachers
class Teacher: 

    #Attribute: name, course taught
    def __init__(self,name,course):
        self.name=name
        self.course=course

    #Method: print the name and course
    def show(self):
        print("Name: {}.course: {}".format(self.name, self.course))

2. Object: instantiation of class

teacher1=Teacher("Jone","Math")
teacher2=Teacher("Hance","Computer")

In this case, teacher is a class, and teacher1 and teacher2 are the specific teacher objects we created. When we enter the above code, Python will automatically call the default__ init__ Initial constructor to generate a concrete object. The keyword self is a very important parameter, which represents the created object itself. That is, self can refer to any instantiated object.

2.2 class variables and instance variables

1. Class variable: located inside the class and outside the function, it is common to all instantiated objects.

2. Instance variable: located in the function body and owned by the current instance object.

3. Visit:

Class variable: class name Variable name or self__ class__. Variable name. self.__class__ Automatically return the class name of each object.

Instance variable: object name Variable name or self Variable name

 4. Example:

#Teachers
class Teacher: 

    num=0 #Class variable

    #Attribute: name, course taught
    def __init__(self,name,course):
        self.name=name
        self.course=course
        Teacher.num=Teacher.num+1

    #Method: print the name and course
    def show(self):
        print("Name: {}.course: {}".format(self.name, self.course)

#instantiation 
teacher1=Teacher("Jone","Math")
teacher2=Teacher("Hance","Computer")
#Call class object
print(Teacher.num) #Printing method 1
print(teacher1.__class__.num)#Print mode 2

Class 2.3 method

Methods that belong to classes only, not concrete instances. Methods belonging to a class do not use the self parameter, but use the parameter cls to represent the class itself. Class methods are often described with the @ classmethod modifier.

#Teachers
class Teacher: 

    num=0 #Class variable

    #Attribute: name, course taught
    def __init__(self,name,course):
        self.name=name
        self.course=course
        Teacher.num=Teacher.num+1

    #Method: print the name and course
    def show(self):
        print("Name: {}.course: {}".format(self.name, self.course)
    
    # Define class methods and print the number of teachers
    @classmethod
    def total(cls):
        print("Total: {0}".format(cls.num))


#instantiation 
teacher1=Teacher("Jone","Math")
teacher2=Teacher("Hance","Computer")
#Call class method
Teacher.total()

2.4 private properties and private methods of class

The private properties and methods of the class are double underlined__ start. Private properties or methods cannot be used or accessed directly outside the class.

class Teacher: 

    num=0 #Class variable

    #Attribute: name, course taught
    def __init__(self,name,course):
        self.__name=name ##Declare name as a private variable
        self.course=course
        Teacher.num=Teacher.num+1

    #Method: print the name and course
    def __show(self):##Declare show as a private property
        print("Name: {}.course: {}".format(self.__name, self.course)
   
#instantiation 
teacher1=Teacher("Jone","Math")

#The following command will report an error
print(teacher1.__name)
teacher1.__show()

2.5 -@property decorator

@The property decorator can call a method disguised as a property.

class Teacher: 

    num=0 #Class variable

    #Attribute: name, course taught
    def __init__(self,name,course):
        self.__name=name ##Declare name as a private variable
        self.course=course
        Teacher.num=Teacher.num+1

    #Method: print the name and course
    @property
    def show(self):##
        print("Name: {}.course: {}".format(self.__name, self.course)
   
#instantiation 
teacher1=Teacher("Jone","Math")
teacher1.show  
##After adding the decorator @property to the function, the calling function can be called directly without parentheses. 
#Name:Jone  course:Math

2.6 inheritance of class

First define the base class or parent class, and then create a child class by class subclass name (parent class name).

For example, teachers and students belong to the same school members and have the attributes of name and age, but teachers have the exclusive attribute of giving courses and students have the exclusive attribute of score. You can define a school member parent class and two subclasses.

# Create parent school member
class SchoolMember:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print(self):
        # Print personal information
        print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")


# Create a subclass Teacher
class Teacher(SchoolMember):

    def __init__(self, name, age, course):
        SchoolMember.__init__(self, name, age) # Initialize with parent class
        self.course = course

    # Method rewrite
    def print(self):
        SchoolMember.print(self)
        print('course: {}'.format(self.course))


# Create subclass Student
class Student(SchoolMember):

    def __init__(self, name, age, score):
        SchoolMember.__init__(self, name, age)
        self.score = score

    def tell(self):
        SchoolMember.tell(self)
        print('score: {}'.format(self.score))


teacher1 = Teacher("Jone", 44, "Math")
student1 = Student("Mary", 12, 99)

teacher1.print() 
student1.print()

super() keyword to call the parent class method:

In the subclass, you can directly call the corresponding methods of the parent class through the super keyword to simplify the code. In the following example, the student subclass calls the print () method of the parent class. super().print() is equivalent to schoolmember print(self). When you use the Python super() keyword to call the parent method, take care to remove the parameter self in parentheses.

# Create subclass Student
class Student(SchoolMember):

    def __init__(self, name, age, score):
        SchoolMember.__init__(self, name, age)
        self.score = score

    def tell(self):
        super().print() # Equivalent to schoolmember print(self)
        print('score: {}'.format(self.score))

That's all for today's study. The above are learning records for reference only!

Keywords: Python Class OOP object

Added by Trek15 on Wed, 02 Mar 2022 02:20:42 +0200