Object Oriented Basics
programming ideas
Programming thinking: The thinking mode of programmers when they encounter problems and solve problems.
1. Procedural programming (poor man's mind) - basic syntax, logic
2. Functional programming (petty bourgeoisie thinking) - mastering functions (there are functions for functions, and there are no functions to create functions)
3. Object-oriented programming (rich thinking) - have classes, objects (variables, functions)
Recognize classes and objects
1. What is a class and what is an object
A class is a collection of objects with the same functionality and the same properties - an abstract concept
An object is an instance of a class (a concrete representation of a class)
A class is a type, a category
like:
Human is a class, the concrete should be human is its object
Computer is a class and this computer on my desk is its object
The cup is the class and the three cups on my desk are its objects
list is the class, [10, 20] is the object of the list
2. Define a class (create a class)
Use code to describe clearly what functions this class has and which objects have the same properties.
function - function
properties - variables that hold data
grammar:
class class name:
(indented) class documentation
(indented) the content of the class
illustrate:
1)class - keyword; fixed writing
2) Class name - the programmer's own name (in camel case and the first letter is capitalized; camel case - the first letter of the word is capitalized from the second word)
3): - Fixed notation
4) Class documentation - multi-line comments
5) Contents of the class - same function and same properties; consists of methods (object methods, class methods, static methods) and properties (object properties, class properties)
method - a function defined in a class
properties - variables defined in a class
class Person: '''Humanity''' num = 61 # num is the attribute def eat(self): # eat is the way print('Have a meal') def sleep(self): print('sleep')
3. Create objects
Syntax: classname() - Creates an object corresponding to the specified class and returns the object
p1 = Person() p2 = Person() print(p1) print(p2)
methods in a class
Method: A function defined in a class is used to describe the functionality it has
Methods in a class: object methods, class methods, static methods
1) Object method
a. How to define: define the function byte in the class
b. How to call: call through the object - object.xxx()
c. Features: It has its own parameter self. When calling an object method through an object, the parameter self does not need to be passed. The system will automatically pass the current object to self, and whoever calls self will point to it.
d. When to use: If you need to use object properties to implement the function of the function, use object methods
2) class method
a. How to define: add the decorator '@classmethod' before defining the function
b. How to call: call by class - class name.xxx
c. Features: comes with parameter cls, no need to pass parameters when calling, the system automatically passes the current class to cls.
d. When to use: If you don't need object attributes to implement functions and need classes, you should use class methods
3) Static method
a. How to define: add the decorator '@staticmethod' before defining the function
b. How to call: call by class - class name.xxx
c. Features: no features
d. When to use: Use static methods to implement functions that neither need object attributes nor class attributes
class A: def func1(self): print(f'self:{self}') print('object method') @classmethod def func2(cls): print('class method') @staticmethod def func3(): print('static method') # call object method from object a = A() b = A() print(f'a:{a}') a.func1() # Calling a class method from a class A.func2() # Calling static methods from a class A.func3()
initialization method
1. The magic method
A built-in method whose method name starts with '__' and ends with '__' is a magic method
All magic methods are called automatically under certain circumstances.
Commonly used magic methods: __init__ method, __repr__ method
1)__repr__ method:
When printing an object, it will automatically call the __repr__ method in the class corresponding to the object to customize the printing rules (what is the return value of the function, what is the printing result of the object),
The return value must be a string.
class A: def __repr__(self): # Left and right are two underscores return 'abc' a1 = A() print(f'a1:{a1}') a2 = A() print(f'a2:{a2}')
2)___init__ method:
When an object of a class is created, the __init__ method in the class is automatically called
class B: def __init__(self): print('init method') b1 = B() b2 = B() class C: # When adding an __init__ method to a class, you can add parameters and function bodies at will, except for the method name and method type. def __init__(self, x, y): print('C of init method') # Whether or not parameters are required when creating an object of a class, and passing parameters are required, which is determined by the __init__ method in the class c1 = C(10, 20) c2 = C(100, 200) c3 = C(x=1, y=2)
Attributes
1. Attributes: divided into object attributes and class attributes
1) Class attributes:
a. How to create: define a variable directly in the class, this variable is the class attribute
b. How to use: use by class - class.xxx
c. When to use: Use class attributes when the attribute value will not be different from object to object
2) Object properties:
a. How to create: Defined in the ___init___ method of the class in the form of 'self. attribute name = value'
b. How to use: use through objects - object.property name
c. When to use: Use class attributes when the attribute value will be different for different objects
class A: # x is a class attribute x = 100 # name and num are object properties def __init__(self): self.name = 'Xiao Ming' self.num = 10 # Use class properties directly print(A.x) # Modify the value of a class attribute A.x = 200 print(A.x) # Using object properties a = A() print(a.name, a.num) # Modify the value of an object property a.name = 'little red' a.num = 11 print(a.name, a.num)
2. How to assign initial values to object properties
class Person: def __init__(self, name, gender='male'): self.name = name # Assignment with parameter without default value self.age = 1 # Assign a fixed value (cannot be modified) self.gender = gender # Use parameters with default values to assign values (can be modified) def __repr__(self): # return f'name:{self.name}, age:{self.age}, gender:{self.gender}' return str(self.__dict__) p1 = Person('Xiao Ming') print(p1.name, p1.age, p1.gender) p2 = Person('little flower', 'Female') print(p2.name, p2.age, p2.gender) print(p1) # {'name': 'Xiao Ming', 'age': 1, 'gender': 'male'} print(p2) # {'name': 'Xiaohua', 'age': 1, 'gender': 'female'}
Exercise 1: Define a class of a circle, with properties: radius (object property) and pi (class property), with methods to find perimeter and area
class Circle: pi = 3.1415926 def __init__(self): self.r = 2 # When implementing functions in a class, if the required data is an attribute, no additional parameters need to be provided def get_area(self): # self = c1, self = c2 (who calls to whom) # If you need class attributes to provide directly with the class # If you need object properties use self to provide return Circle.pi * self.r ** 2 def get_perimeter(self): return 2 * Circle.pi * self.r c1 = Circle() c2 = Circle() c2.r = 3 print(c1.get_area(), c2.get_area())
Exercise 2: Create a rectangle class (extend the content of the class according to life)
class Rectangle: def __init__(self, long, wide): self.long = long self.wide = wide def area(self): return self.long * self.wide def perimeter(self): return 2 * self.long + 2 * self.wide def __repr__(self): # return f'length:{self.long}, width:{self.wide}, area:{self.area()}, perimeter:{self.perimeter()}' return f'<{str(self.__dict__)[1:-1]}>' r1 = Rectangle(10, 20) print(r1.area(), r1.perimeter()) print(r1) # Length:10, Width:20, Area:200, Circumference:60 r2 = Rectangle(5, 5) print(r2) # <'long': 5, 'wide': 5>
Attribute addition, deletion, modification and inspection
1. In object-oriented programming, objects can be used directly instead of dictionaries
class Student: def __init__(self, name, age=18, score=0): self.name = name self.age = age self.score = score def __repr__(self): return str(self.__dict__) stu1 = Student('little red', 12, 67) stu2 = Student('little flower', 19, 100) print(stu1, stu2)
2. The object properties of the object support adding, deleting, modifying and checking
1) lookup - get attribute value
a.Object.Attribute - Get the value of the specified attribute (the attribute does not exist, an error is reported)
b.getattr( object, attribute name) - get the value of the specified attribute (the attribute does not exist, an error is reported)
c.getattr( object, attribute name, default value) - get the value of the specified attribute
print(stu1.name) # little red print(getattr(stu2, 'name')) # little flower # print(stu1.gender) # Error! # print(getattr(stu1,'gender')) # report an error print(getattr(stu1, 'gender', 'male')) # male
2) Add and modify
a.Object.Attribute = Value - When the attribute exists, modify the value corresponding to the specified attribute; when the attribute does not exist, add the attribute to the object.
print(stu1) # {'name': 'Xiaohong', 'age': 12, 'score': 67} stu1.age = 22 print(stu1) # {'name': 'Xiaohong', 'age': 22, 'score': 67} stu1.gender = 'Female' print(stu1) # {'name': 'Xiaohong', 'age': 22, 'score': 67, 'gender': 'female'}
b.setattr( object, attribute name, value) - when the attribute exists, modify the value corresponding to the specified attribute; when the attribute does not exist, add the attribute to the object.
setattr(stu1, 'score', 76) print(stu1) # {'name': 'Xiaohong', 'age': 22, 'score': 76, 'gender': 'female'} setattr(stu1, 'study_id', '001') print(stu1) # {'name': 'Xiaohong', 'age': 22, 'score': 76, 'gender': 'female', 'study_id': '001'}
attr related functions can dynamically manipulate object attributes
value = input('Please enter the data you want to view:') # print(stu1.value) print(getattr(stu1, value))
3) delete
del object.attribute - deletes the specified attribute
delattr( object, attributeName) - dynamically determine the attribute to delete
print(stu1) # {'name': 'Xiaohong', 'age': 22, 'score': 76, 'gender': 'female', 'study_id': '001'} del stu1.age print(stu1) # {'name': 'Xiaohong', 'score': 76, 'gender': 'female', 'study_id': '001'} delattr(stu1, 'name') print(stu1) # {'score': 76, 'gender': 'female', 'study_id': '001'}
4) Determine whether the attribute exists
hasattr( object, attribute)
print(hasattr(stu1, 'name')) # False print(hasattr(stu1, 'score')) # True
inherit
1. Inheritance - let the subclass directly use the properties and methods of the parent class
The parent class is a large class, and the subclass is a small category under the large class
2. The syntax of inheritance
class class name (parent class):
(indented) class documentation
(indented) the content of the class
Note: If you do not write a parent class when defining a class, this class inherits object (base class) by default.
# class Person: == class Person(object): class Person: pass
class A: a = 100 def __init__(self): self.b = 10 self.c = 20 def func1(self): print('object method') @classmethod def func2(cls): print('class method') @staticmethod def func3(): print('static method') class B(A): pass print(B.a) x = B() print(x.b, x.c) x.func1() B.func2() B.func3()
3. Subclass to add content
While the subclass has the properties and methods of the parent class, it often needs some properties and methods that are unique to it.
1) Add class attributes and methods
Define new class properties and new methods directly in subclasses
2) Add object properties
You need to call the __init__ method of the parent class through super() in the __init__ method of the subclass to inherit the object attributes of the parent class
class C(A): m = 11 def __init__(self): super().__init__() # Call the __init__() of the parent class of the current class self.name = 'Xiao Ming' def func11(self): print('C object method of') @classmethod def func22(cls): print('C class method of') @staticmethod def func33(): print('C static method of') def func1(self): print('C object method 2') print(C.a, C.m) x = C() print(x.name) print(x.b, x.c)