Overview of Object-Oriented Programming Day 24

Three Questions in Life

What is an object
    The real thing with certain characteristics and behaviors is the object, everything is the object. 
What is a class
    A combination of a series of objects with the same characteristics and behavior is called a class.In programming, only classes can have objects.

1. What is Object Oriented
Object-oriented and process-oriented are both a programming idea, one is process, the other is object, object-oriented is to treat everything as
Objects, we need to do things with objects to help us do them, not as process-oriented as we have to think about everything on our own
Things are the same.
2. Why use Object Oriented
Environments: Every company's business is growing, and we must have a scalable approach to this situation.
Advantages:
1. Extensibility.Everything is an object, and adding attributes to an object does not have a characteristic effect.
2. It simplifies the programmer's operation, so we don't have to go through things one step at a time, we just need to leave it to the object to complete it
Disadvantages:
1. Increased design complexity.We need to design the right objects beforehand to avoid over-design.
2. Program controllability is reduced.
3. How to use Object Oriented

Create Classes and Objects

# Define classes using class Class name:] Define a class
# Specification for class names: Use hump nomenclature at the beginning of general capitalization
class SHOldboyStudent:
    # Use variables to define the characteristics of class objects (often referred to as attributes)
    # Student Union Name, Age, Gender, School
    age = '11'
    name = 'egon'
    gender = 'female'
    school = 'HSOldboy'
    # Use functions to define the behavior of objects (often referred to as methods)
    # There can be multiple behaviors, and each time a behavior is defined, a parameter is automatically added self
    def say_hi(self):
        print('hi, i am boy!')

    def say_hello(self):
        print('hello, i am boy')
        
# To create an object, you can use the Class Name()]To create an object
student = SHOldboyStudent()

Properties of Classes

Notes:
   The object's namespace and the class's namespace are relatively independent, and public attributes are included in the class.Classes may not have attributes.
Search order for attributes
Start with the namespace of the object===== class.

View properties (both object and class):

# To create an object, you can use the Class Name()]To create an object
student = SHOldboyStudent()
# View namespaces in classes
print(SHOldboyStudent.name, SHOldboyStudent.__dict__)
# View the object's namespace
print(student.__dict__)
# Access corresponding properties by object name
print(student.name)

# Result:
# egon {'__module__': '__main__', 'age': '11', 'name': 'egon', 'gender': 'female', 'school': 'HSOldboy', 'say_hi': <function SHOldboyStudent.say_hi at 0x037E4F60>, 'say_hello': <function SHOldboyStudent.say_hello at 0x037F8078>, '__dict__': <attribute '__dict__' of 'SHOldboyStudent' objects>, '__weakref__': <attribute '__weakref__' of 'SHOldboyStudent' objects>, '__doc__': None}
# {}  # The object's namespace is empty
# egon  # But the object can access the value, why? Because the attributes in the class are the same for each object, there is no need to save two copies, just go to the class to find them when the object needs them.

Add attributes (objects only):

# Adding attributes only adds to objects, and attributes in classes do not change
student = SHOldboyStudent()
student.height = 15
print(student.height)  # Give Object student Added a height attribute so you can access
# print(SHOldboyStudent.height)  This is an error, because there is no such property in the class

Delete attributes (objects only)

# Deleting attributes simply deletes attributes in the object, and attributes in the class do not change
student = SHOldboyStudent()
student.height = 15
print(student.height)  # Give Object student Added a height attribute so you can access
del student.height
print(student.height)  # You get an error when you go to view it, because at this point height Property has been deleted
# print(SHOldboyStudent.height)  This is an error, because there is no such property in the class

Change properties (object only)

# change attributes, Attributes in classes do not change
student = SHOldboyStudent()
print(student.name)    # egon
student.name = 'hu'
print(student.name)   # hu
print(SHOldboyStudent.name)  # egon

Method of class

Special method of class_u init_u

# Define classes using class Class name:] Define a class
# Specification for class names: Use hump nomenclature at the beginning of general capitalization
class SHOldboyStudent:
    # Use variables to define the characteristics of class objects (often referred to as attributes)
    # Student Union Name, Age, Gender, School
    age = '11'
    name = 'egon'
    gender = 'female'
    school = 'HSOldboy'
    # Use functions to define the behavior of objects (often referred to as methods)
    # There can be multiple behaviors, and each time a behavior is defined, a parameter is automatically added self
    def say_hi(self):
        print('hi, i am boy!')

    def say_hello(self):
        print('hello, i am boy')
Specify a defined student class
Defined student class questions:
The public attributes we define in the class are name, age, gender, etc. We want to think that our students all have different names, ages, and genders, but it is obviously unreasonable that we will have the same attributes through the above classes. We can't define these attributes, we should define these attributes by each object itself, so
With this version below.

Improved version:

class SHOldboyStudent:
    # There are currently no public attributes of this student class.
    def say_hi(self):
        print('hi, i am boy!')

    def say_hello(self):
        print('hello, i am boy')

# Create an object Student One
stu1 = SHOldboyStudent()
# Add attributes to students
stu1.name = 'egon'
stu1.age = 11
stu1.gender = 'female'

# Create an object Student Two
stu2 = SHOldboyStudent()
# Add attributes to students
stu1.name = 'hu'
stu1.age = 12
stu1.gender = 'male'

Question 2: Although this solves the problem of public attributes, our objects need to add attributes again each time they are created, and most of the attributes added are the same, so we think of using functions to solve such problems:

class SHOldboyStudent:
    # There are currently no public attributes of this student class.
    def say_hi(self):
        print('hi, i am boy!')

    def say_hello(self):
        print('hello, i am boy')

def add_attribute(obj, name, age, gender):
    obj.name = name
    obj.age = age
    obj.gender = gender

# Create an object Student One
stu1 = SHOldboyStudent()
# Add attributes to students
add_attribute(stu1, 'egon', 11, 'female')
print(stu1.name)

# Create an object Student Two
stu2 = SHOldboyStudent()
# Add attributes to students
add_attribute(stu1, 'hu', 11, 'male')
print(stu1.name)

Question 3: In this case we still need to redefine a function and put the object we created into it. It's time for our u init_u file to work

_u init_u File Role
In order to call this function directly to copy when creating an object, we have redefined the problem of adding object properties above.
Be careful:
1. You need to customize different attribute values for each object
2. u init_u Automatically executes when an object is created
3. u init_u The first self parameter refers to the object itself and does not need to be passed
class SHOldboyStudent:
    # this init file
    def __init__(self, name, age, gender):  # The parameter self is the obj object itself, which is just normalized here
        self.name = name
        self.age = age
        self.gender = gender
        
    def say_hi(self):
        print('hi, i am boy!')

    def say_hello(self):
        print('hello, i am boy')


# Create an object Student One
stu1 = SHOldboyStudent('egon', 11, 'female')  # All you need to do here is pass in three object property values, which python has already directly encapsulated for us.

# Create an object Student Two
stu2 = SHOldboyStudent('hu', 11, 'male')

Binding of Objects and Methods

Three Questions in Life

What is the binding method
A binding method refers to a binding relationship between an object and a method. Why use binding methods
Typically, the behavior of an object (that is, the method of a class) requires access to the object's data, or to modify the object's data, so it makes no sense to call the class directly without creating the object, so it binds the object to the function. How to use binding methods
In a class, python itself has already bound us, that is, passed in the object itself directly through the self parameter.

1. Class to invoke method

# Class call methods are equivalent to using normal functions, passing whatever value is passed
class
SHOldboyStudent: # There are currently no public attributes of this student class. def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def say_hello(self): print(self) print('hello, i am boy') # 1.Error if no value is passed SHOldboyStudent.say_hello(111)

2. Object calls class methods

class SHOldboyStudent:
    # There are currently no public attributes of this student class.
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def say_hello(self):
        print(self)
        print('hello, i am boy')

# 1.You can pass values directly because objects and methods are already bound
student = SHOldboyStudent('egon', 11, 'male')
student.say_hello()

Small case:

Create a hero class, create two heroes to chop each other

class Hero:
    def __init__(self, blood, name, hero_type, q, w, e):
        self.blood = blood  # Blood Volume
        self.name = name  # Name
        self.hero_type = hero_type  # Hero Type
        self.q = q   # q Skill Injuries
        self.w = w   # w Skill Injuries
        self.e = e   # e Skill Injuries

    def hurt(self, enemy, skill):
        print('{name}towards{enemy}Released{skill}Skill,Cause injury{hurt},Enemy{enemy}Remaining blood volume{blood}'.format(
            name=self.name,
            enemy=enemy.name,
            skill=skill,
            hurt='self.%s' % skill,
            blood=0 if enemy.blood - self.q < 0 else enemy.blood - self.q
        ))
        enemy.blood = enemy.blood - self.q
        if enemy.blood < 0:
            print('Enemy{enemy}Death'.format(enemy=enemy.name))


# Create Two Heroes
yasuo = Hero(200, 'yasuo', 'zhanshi', 50, 100, 150)
huangzi = Hero(200, 'huangzi', 'zhanshi', 60, 80, 180)

yasuo.hurt(huangzi, 'q')
yasuo.hurt(huangzi, 'e')

Keywords: Python Attribute Programming

Added by salasilm on Fri, 17 May 2019 23:59:20 +0300