Class and Object Foundation

Keywords: Python Programming Attribute

Catalog

Introduction to Object-Oriented Programming

PROCESS-ORIENTED PROGRAMMING

The core is the word "process". Process refers to the steps of doing things, that is, what to do first and then what to do.

Writing programs based on this programming idea is like a factory assembly line, a mechanical way of thinking.

Advantages: Clear logic, complex problem flow, and simplification.

Disadvantage: poor scalability.

object-oriented programming

The core of object-oriented programming is the word object, which refers to the combination of features and skills. Writing programs based on this programming idea is like creating the world, a God-like way of thinking.

Advantages: High scalability.

Disadvantage: Programming is much more complex than process-oriented.

Classes and objects

What is a class? Type, Classification

First define the class, then call the class to generate the object.

  • In the real world: the object is a concrete thing, and the class is abstractly summarized by the development of human civilization.

  • In the program: must follow the first class, then object

Summary:

Objects are the combination of features and skills, and classes are the combination of a series of objects with the same characteristics and skills.

Definition class

# Class names use hump nomenclature
class Student: 
    school = 'oldboy'
    def choose_course(self):
        print('choose course')
    
    def learn(self):
        print('learn')

What happens in defining classes:

  1. When a class is defined, it generates an empty namespace
  2. The name defined in the class is thrown into the namespace of the class.

Note: Classes already generate namespaces at the definition stage and execute code inside the class when executing python files

class Student: 
    school = 'oldboy'
    def choose_course(self):
        print('choose course')
    
    def learn(self):
        print('learn')
        
        
print(Student.__dict__)  # View all names in the class namespace

'''
{'__module__': '__main__', 'school': 'oldboy', 'choose_course': <function Student.choose_course at 0x0000010EF2FD3510>, 'learn': <function Student.learn at 0x0000010EFA1A0950>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
'''

Object creation and use

Class operations

class Student: 
    school = 'oldboy'
    def choose_course(self):   # self is the object itself
        print('choose course')
    
    def learn(self):
        print('learn')
        
print(Student.school)  # lookup

Student.school = 'oldgirl'   # modify
print(Student.school)   
'''
oldgirl
'''

Student.address = 'Shanghai'  # increase
print(Student.address)

del Student.address    # delete


Student.choose_course(123)  # Need parameters in parentheses

Namespace generation:

  1. Namespaces of classes have been created at the definition stage
  2. Object namespace, generated when calling a class
class Student():
    school = 'oldboy'

    def choose_course(self):
        print('choose course')

    def learn(self):
        print('learn')


stu1 = Student()
stu2 = Student()
stu3 = Student()

print(stu1.school)
stu1.choose_course()
stu1.learn()

Define _init_ functions within classes

_ init_ automatically triggers the function when the class is called, initializing certain properties for the object

class Student():
    school = 'oldboy'

    def __init__(self):
        print('Here is__init__')


    def choose_course(self):
        print('choose course')

    def learn(self):
        print('learn')


stu1 = Student()
stu2 = Student()
stu3 = Student()

print(stu1.school)
stu1.choose_course()
stu1.learn()

What happens to the calling class:

  1. First, an empty object is generated, which is the object's namespace.
  2. It automatically triggers _init__
  3. It passes the object along with the parameters in parentheses to the _init_ function.
class Student():
    school = 'oldboy'

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


    def choose_course(self):
        print('choose course')

    def learn(self):
        print('learn')


stu1 = Student('cwz', 23, 'male')

print(stu1.name)
print(stu1.age)
print(stu1.sex)

'''
cwz
23
male
'''

Search order of objects and classes

class Student():
    school = 'oldboy'

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


    def choose_course(self):
        print('choose course')

    def learn(self):
        print('learn')


stu1 = Student('cwz', 23, 'male')

print(stu1.__dict__)
print(stu1.name, stu1.school)
'''
{'name': 'cwz', 'age': 23, 'sex': 'male'}
cwz oldboy
'''

Object and class lookup order:

  1. Object. Attribute, if the object itself has, the priority is to find the object's own
  2. If the object itself does not exist, then go to the class to find, if there is no class, then report an error.

Object binding method

class Student():
    school = 'oldboy'

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


    def choose_course(self):
        print('choose course')

    def learn(self):
        print('learn')

# print(Student.learn)
# Student.learn(133)

stu1 = Student('qwe', 20, 'male')
stu1.learn()

Functions within classes are mainly for objects:

  1. The function inside the class is called by the class. The function is just a normal function. The ordinary function needs to receive several parameters and then it has to pass in several parameters.
  2. An object calls a binding method called an object, and when different objects call the binding method, different objects are passed into the binding method.
  3. The binding method of an object is called by an object. The special thing is that the object is passed into the method as the first parameter.
class Student():
    school = 'oldboy'

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
        print('stu:', self)


    def choose_course(self):
        print('choose course')

    def learn(self):
        print('learn')

# print(Student.learn)
# Student.learn(133)

stu1 = Student('qwe', 20, 'male')
stu2 = Student('cwz', 21, 'male')
stu1.learn()
print('stu1', stu1)
stu2.learn()
print('stu2', stu2)
print(stu1.learn)

'''
stu: <__main__.Student object at 0x0000019E249E2128>
stu: <__main__.Student object at 0x0000019E249E2198>
learn
stu1 <__main__.Student object at 0x0000019E249E2128>
learn
stu2 <__main__.Student object at 0x0000019E249E2198>
<bound method Student.learn of <__main__.Student object at 0x0000019E249E2128>>
'''

Small exercises

'''
//Man and dog bite each other
'''

class Person:
    def __init__(self, name, aggr, life):
        self.name = name
        self.aggr = aggr
        self.life = life

    # Man bites dog
    def bite(self, dog):
        if dog.life < 0:
            return True
        dog.life -= self.aggr

        print(
            f'''
            //Man {self.name} bites dog {dog.name}
            //Dog bleeding {self.aggr}
            //Dog's Remaining Blood Volume {dog.life}
            '''
        )


class Dog:
    def __init__(self, name, dog_type, aggr, life):
        self.name = name
        self.dog_type = dog_type
        self.aggr = aggr
        self.life = life

    # Dog biting method
    def bite(self, person):
        if person.life < 0:
            return True
        person.life -= self.aggr

        print(
            f'''
            //Dog {self.name} bites {person.name}
            //Human blood loss {self.aggr}
            //Remaining blood {person.life}
            '''
        )


p1 = Person('neo', 300, 400)
d1 = Dog('Chinese rhubarb', 'Hyacinth', 200, 500)

while True:
    flag1 = p1.bite(d1)
    if flag1:
        break

    flag2 = d1.bite(p1)
    if flag2:
        break

Posted by kb9yjg on Wed, 09 Oct 2019 13:37:38 -0700