Object-oriented is composed of encapsulation, inheritance and polymorphism
Encapsulation: write properties and methods into the class.
Inheritance: subclasses inherit methods and properties of the parent class.
Polymorphism: Subclasses rewrite the parent class and then instantiate them into different objects to produce different results
Class and object
class Gun():
def __init__(self,width):
self.length = 100
self.width = width
def shoot(self):
print('bang')
print(self)
wuzi = Gun(3)
print(wuzi)
wuzi.blood_loss = 30
Relationship: Use a class to instantiate into an object. Instantiation means creation. A class can create multiple objects. For
example, Gun above is a class, and wuzi is an instantiated object.
Instantiated object = class()
Instance/object method
The class contains properties and methods, that is, variables and functions.
Using the shoot function is an instance method or an object method.
Calling a method
wuzi.shoot()
what is self
Refers to the object that calls the function . As in the above example, the memory address of the self object printed out is the same as the memory address of wuzi, and the self is the object that calls the function.
Attributes
Object/instance properties
As in the above example, the attributes added outside the class are called object attributes, and blood_loss is the attribute name
__init__ method
Function: Initialize the object.
As in the above example:
when the attribute is instantiated, the length attribute is automatically generated; at the same time, we can also set the attribute with parameters to the object, such as width
__str__ method
When print outputs an object, it will print out the memory address of the object. If you define the __str__ method, you can return the desired output
def __str__():
return 'gun'