Python Basics - object oriented Basics (exercise)

1, Definition

Object oriented programming: OOP
The focus of object-oriented programming is who will do it. Compared with functions, object-oriented is a larger encapsulation, which encapsulates multiple methods in an object according to responsibilities
Attribute, behavior
First, there are classes, which abstract and classify specific things, and then regenerate objects according to classes
Class: it is a general term for a group of things with the same characteristics or behavior. It is abstract and cannot be used directly

  • A feature is actually a variable, which is called an attribute in a class;
  • Behavior is actually a function, which is called a method in a class;
  • Class is actually an abstract concept composed of attributes and methods

2, Object oriented basic syntax

# There are two objects:
# Xiao Ming is 23 years old. He is 180cm tall and weighs 75kg. He can sleep
# Xiaohong is 21 years old, 170cm tall and 58kg heavy. She can sleep


# Create a class and define a class name
class Person(object):
    def __init__(self, name, age, height, weight):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight

    def sleep(self): # behavior
        print('be sleeping!')


# A Person object p1 is created using the Person class
p1 = Person('Xiao Ming', 23, '180cm', '75kg')
p1.sleep()

p2 = Person('Xiao Hong', 21, '170cm', '58kg')
p2.sleep()

3, Object properties

  • Point of use Syntax, you can add attributes to an object;
  • Support dynamic attributes in python (try to avoid using dynamic attributes);
  • When creating an object, you can not set attributes. After creating it, you can manually add attributes to the object (add attributes dynamically);
  • __init__ Method requires that an object must have some properties when it is created
    
class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def say_hello(self):
        print('Hello, my name is{},I{}Years old'.format(self.name, self.age))
        # print('Hello, my name is{},I{}Years old'.format(self.name, self.money) # An error will be reported because the money attribute is added manually and dynamically later


# __ init__  Method requires that an object must have some properties when it is created
s1 = Student('jerry', 18, 100)
print(s1.name)

print(s1.addr)   # An error will be reported because there is no addr attribute. AttributeError: 'Student' object has no attribute 'addr'

# After the object is created, you can dynamically add attributes at any time
s1.money = 1000
print(s1.money)

print(s1.age)  # 18
s1.age = 20
print(s1.age)  # 20

s1.say_hello() # It will print successfully. If there are dynamic attributes in print, an error will be reported

s2 = Student('chris', 20, 98) 
s2.say_hello() # Will print successfully

4, self pointing

  1. The new method of Dog class will be called to apply for a section of memory space
  2. hold __init__ Inside self Point to this memory space
    
  3. call __init__ Method to put your own data in memory
    
  4. Assign this memory space to the variable d1, that is, the last d1 will also point to this memory space
  5. self can only be used in__ init__ Used in
class Dog(object):
    def __init__(self, name, color):
        self.xingming = name
        self.yanse = color

    def say_hello(self):  # self refers to who calls this method
        print('Hello, I'm{}'.format(self.xingming))

d1 = Dog('chinese rhubarb', 'white')
print(d1.yanse)
d1.say_hello() # d1 called say_hell0() method, self refers to d1, self Xingming refers to the name 'rhubarb' of d1

d2 = Dog('Wangcai', 'black')
d2.say_hello()

5, Magic method

In class, in __ Start and start with __ The way to end, we call it magic(Magic Methods )

Features: without manual calling, they will be called automatically at the appropriate time

  • __str__Method must have a return value,And it's a string;Automatically called when an object is to become a string;
    
  • __repr__
    
  • __del__This method is called automatically when an object is destroyed
    
class Person(object):
    def __init__(self, name, age):
        print('__init__Function called!!!!')
        self.name = name
        self.age = age

    def __str__(self):
        # Automatically called when an object is to become a string
        # __ str__  Method must have a return value and be a string
        print('__str__Called!!!!!')
        # return 'hehe'
        return 'name:' + self.name + ', age:{}'.format(self.age)

    def __repr__(self):
    	# When you need to modify the output of an object
        return 'name:' + self.name + ', age:{}'.format(self.age)
		return 'yes'
		
    def __del__(self):
        # This method is called automatically when an object is destroyed
        print('hehehehe')
        del self

    def sleep(self):
        print('{}be sleeping'.format(self.name))

p1 = Person('jerry', 18) # Automatically called, will print '__ init__ Function called
# print(p1)  # <__main__.Person object at 0x0069F7D0>
print(p1)  # {name:jerry,age:18}

Vi==

1,==

  • Two objects do == After comparison, the of the object will be called __eq__ method;
    
  • If not modified __eq__method,Two objects == The default is to compare memory addresses
    
# 1,
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person('zhangsan', 18)
p2 = Person('zhangsan', 18)

print(p1 == p2) # False, object = = if the eq method is not modified, the memory address is compared by default
print(p1 is p2) # False

n1 = ['zhangsan', 'lisi', 'wangwu']
n2 = ['zhangsan', 'lisi', 'wangwu']
print(n1 == n2)  # True, list = = compares contents, is compares memory addresses
print(n1 is n2)  # False
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        # if self.name == other.name and self.age == other.age:
        #     return True # If the name and age are the same, it returns true; otherwise, it returns false
        # return False
        return self.name == other.name and self.age == other.age  # equivalence


p1 = Person('Zhang San', 18)
p2 = Person('Zhang San', 18)

p3 = p2 # python's assignment is the assignment of memory address, that is, the address of p2 is given to p3, pointing to the same memory address. p3 does not create a new object, and the format of the created object is such as P1 and p2
print(p3 is p2)  # True
print(p3 is p1)  # False

print(p1 == p2)  # True, the eq method is modified. If the name and age are the same, it returns true
# p1==p2 ==> p1.__ eq__ (P2) is p1==p2 is the EQ method called by P1

print(p1 is p2)  # False

2. Compare the size of two objects

  • Default not supported except == Other than the comparison operation, only rewritten __lt__ Or and __gt__ After the magic method, the comparison operation is supported
    
  • lt: less than   less than    gt: greater than  greater than
    
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __lt__(self, other): # Override lt method
        return self.age < other.age


p1 = Person('chris', 18)
p2 = Person('allen', 19)

print(p1 > p2)  # False

3. Sort objects

  • Using the sort method, the parameter key is passed into the anonymous function to sort the object elements in the list
class Person(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def __lt__(self, other): # Rewrite it methods
        # return self.age < other.age
        return self.score < other.score

p1 = Person('jerry', 18, 98)
p2 = Person('tony', 20, 81)
p3 = Person('henry', 17, 86)

persons = [p1, p2, p3, p4, p5]
persons.sort()

# persons.sort(key=lambda ele: ele.score). When there is no it method (no rewritten code), the 📄 Pass it in

for p in persons:
    print(p.name)
# Dictionary sort
ps = [
    {'name': 'zhangsan', 'age': 18},
    {'name': 'lisi', 'age': 19},
    {'name': 'wangwu', 'age': 17},
    {'name': 'zhaoliu', 'age': 20},
    {'name': 'tianqi', 'age': 16},
    {'name': 'wangba', 'age': 21}
]

# def demo(ele): # It will constantly pass in dictionaries to the parameter ele
#     return ele['age']
# ps.sort(key=demo)
 
ps.sort(key=lambda ele: ele['age']) # You can use lambda expressions for short
print(ps)

7, Object oriented exercises

1. Xiao Ming's weight

# 1. Xiao Ming weighs 75.0kg. Xiao Ming loses 0.5kg every time he runs. Xiao Ming gains 1kg every time he eats.
# When printing Xiaoming, output Xiaoming's name and weight information

class Person(object):
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def run(self):
        self.weight -= 0.5

    def eat(self):
        self.weight += 1

    def __int__(self): # Magic method
        return 100

    def __float__(self): # Magic method
        return 34.5

    def __str__(self):  # Magic method, which is automatically called when a string needs to be returned
        return 'full name:{},weight{}kg'.format(self.name, self.weight)


p1 = Person('Xiao Ming', 75)
p1.run()
p1.run()
p1.run()
p1.eat()
p1.run()

print(p1)
print(str(p1))
print(int(p1))
print(float(p1))

2. House type and furniture

# 2. House has the attributes of house type, total area, remaining area and furniture name list
# The new house has no furniture
# Appends the name of the furniture to the furniture name list
# Judge whether the area of the furniture exceeds the remaining area. If it exceeds the remaining area, it will prompt that the furniture cannot be added;
# Furniture (HouseItem) has name and floor area attributes, where
# bed covers an area of 4 square meters
# The wardrobe covers an area of 2 square meters
# The table covers an area of 1.5 square meters
# Add the above three pieces of furniture to the house
# When printing a house, it is required to output: house type, total area, remaining area and furniture name list

class House(object):
    def __init__(self, type, total_area):
        self.type = type
        self.total_area = total_area
        self.free_area = total_area * 0.5
        self.item_list = [] # Give an empty list

    def add_item(self, item):
        if self.free_area < item.area * 1.5: # It is assumed that the floor area of furniture multiplied by 1.5 is the actual floor area
            print('I can't put it down!')
            return # If you can't put it down, return and then the code won't go again

        self.item_list.append(item.name) # If there is any remaining area, add it inside
        self.free_area -= item.area * 1.5

    def __str__(self):
        return 'House type{},total area{},Remaining area{},Furniture list{}'.format(self.type, self.total_area, self.free_area, self.item_list)


class HouseItem(object):
    def __init__(self, name, area):
        self.name = name
        self.area = area


h1 = House('One bedroom', 20)

bed = HouseItem('Simmons', 4)
chest = HouseItem('wardrobe', 2)
table = HouseItem('table', 1.5)

h1.add_item(bed)
h1.add_item(chest)
h1.add_item(table)

print(h1)

3. Soldiers assigned guns

# 3. Soldier Zhang San has an M416
# Guns can be loaded
# Guns can fire bullets
# If a soldier doesn't have a gun, he can't fire
# If there are no bullets in the gun, it needs to be loaded
# If there are guns and bullets, you can fire


class Solider(object):
    def __init__(self, name, gun=None):  # Default parameter. It can be passed later without gun
        self.name = name
        self.gun = gun

    def fire(self):
        if not self.gun:
            print('You don't have a gun, you can't fire!!!')
            return
        if self.gun.bullet_count == 0:
            print('There are no bullets. We need to load them')
            return

        if self.gun.bullet_count >= 3:
            self.gun.bullet_count -= 3  # Three shots at a time
        else:  # If the bullet is less than 3, the bullet remains 0 after firing
            self.gun.bullet_count = 0
        print('Guns, bullets, fire!!! Remaining{}Fire a bullet'.format(self.gun.bullet_count))


class Gun(object):
    def __init__(self, type, bullet_count=0):  # The default value is 0
        self.type = type
        self.bullet_count = bullet_count


g1 = Gun('m416', 30)
s1 = Solider('Xu Sanduo')
# s1 = Solider('Xu Sanduo', g1) # The instance was assigned to the gun when it was created
s1.gun = g1  # If there is no such sentence, all instances have been created, but s1 did not get the gun, that is, there was no gun at the time of creation, and then a gun was given

s1.fire()

4. Is the point online

# Define a Point class with two attributes X and y, create three Point objects a, B and c, and judge whether c is on the line segment composed of ab
import math

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y


class Line(object):  # Hidden clues: the sum of the lengths of the two segments is equal, that is, on the same segment
    def __init__(self, start_point, end_point):
        self.start_point = start_point
        self.end_point = end_point

    def get_length(self, point1=None, point2=None):  # Gets the length of the line segment, that is, the distance between two points
        point1 = point1 or self.start_point
        point2 = point2 or self.end_point

        return math.sqrt((point2.x - point1.x) ** 2 + (point2.y - point1.y) ** 2) # Square root, math module

    def is_inline(self, point):  # Whether the judgment point is online
        return self.get_length() == self.get_length(self.start_point, point) + self.get_length(self.end_point, point)


p1 = Point(3, 3)
p2 = Point(6, 6)  
p3 = Point(6, 7)  # false this point is not online
p4 = Point(9, 9)  # true the point is on the line

l = Line(p1, p2)
print(l.get_length())  # If no parameters are passed, point1 takes the default value None, and if it is false, continue to take the value self after or start_ Point, or until the first value is true
# print(l.get_length(p1, p3))  # p1 to point1,p3 to point2
print(l.is_inline(p4))

5. Is the point inside the rectangle

Define a class React with start_ x,start_ y. Width, the attribute of height, represents the length and width of the rectangle. Determine whether (x,y) is within the range of the rectangle

# 1,
class React(object):

    def __init__(self, start_x, start_y, width, height):
        self.start_x = start_x
        self.start_y = start_y
        self.width = width
        self.height = height

    def is_inside(self, x, y):
        # if self.start_x < x < self.start_x + self.width and self.start_y < y < self.start_y + self.height:
        #     return True
        # return False
        return self.start_x < x < self.start_x + self.width and self.start_y < y < self.start_y + self.height


r = React(4, 5, 10, 6)
print(r.is_inside(20, 25))  # False
print(r.is_inside(12, 9))  # True
# 2. Add another point class

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

class React(object):
    def __init__(self, start_point, width, height):
        self.start_point = start_point
        self.width = width
        self.height = height

    def is_inside(self, point):
        return self.start_point.x < point.x < self.start_point.x + self.width and self.start_point.y < point.y < self.start_point.y + self.height

sp = Point(10, 18)  # Start point of instantiation rectangle: start_point (i.e. start_x,start_y)
r = React(sp, 20, 25)

p = Point(22, 28)
print(r.is_inside(p))  # True

VIII

Keywords: Python

Added by Dimwhit on Thu, 16 Dec 2021 05:54:11 +0200