Getting Started with Python-4: Classes and Objects

Classes and objects

Object-oriented programming is one of the most effective software writing methods. In object-oriented programming, you write classes that represent things and situations in the real world, and create objects based on these classes. Objects can be said to be ubiquitous in python. Objects simulate the real world with code. Object = attribute + method, the characteristics of an object are called "attributes", and the behavior of an object is called "methods".

**Learn how to create a class: **

The difference in creating functions in a class is to add a self. A class in python can generate countless objects. When an object’s method is called, the object will pass its own reference as the first parameter to the method. .

>>> classBALL:...     def setname(self,name):...         self.name=name
...  def kick(self):...print('my name is %s, oh,who kick me?'%self.name)...>>> a=BALL()>>> a.setname('tom')>>> a.kick()
my name is tom, oh,who kick me?
Python's magic square
>>> classDog():...     def __init__(self,name,age):...         self.name=name
...   self.age=age
...  def sit(self):...print(self.name.title()+' is now sitting')...     def grow(self):...print(self.name.title()+' is '+str(self.age)+' years old')...>>> a=Dog('Tom',6) ####Incoming parameter name,age
>>> a.sit() ###Call the passed parameters directly
Tom is now sitting
>>> a.grow()
Tom is 6 years old

Use class

**Define a car class: **

>>> classCar:...     def __init__(self,make,model,year):...         self.make=make
...   self.model=model
...   self.year=year
...  def get_descriptive(self):...print(self.year+self.model+self.make)...>>> mycar=Car('China','ak','2018')>>> mycar.get_descriptive()
2018 akChina

Assign default values to attributes

classCar:
 def __init__(self,make,model,year):
  self.make=make
  self.model=model
  self.year=year
  self.odo=0
 def get_descriptive(self):print(self.year+ self.model+ self.make)
 def odometr(self):print("this car has "+str(self.odo)+" miles on it")>>> mycar=Car('China','ak','2020')>>> mycar.odometr()this car has 0 miles on it ###The default parameter is zero, so the result is zero

Modify the value of the attribute

Modify the value of the attribute directly
>>> mycar=Car('china','ak','2010')>>> mycar.odo=23 ###Modify directly, let python find the attribute odo directly in the instance and modify it to 23>>> mycar.odometr()this car has 23 miles on it

Modify the value of the attribute through the method
>>> classCar:...     def __init__(self,make,model,year):...         self.odo=0...print(self.year+ self.model+ self.make)...print("this car has "+str(self.odo)+" miles on it")...     def updataodo(self,mileage): ####Re-create an object in it, so that the input parameters are the original default values
...   self.odo=mileage
>>> mycar=Car('china','ak','2020')>>> mycar.updataodo(56)>>> mycar.odometr()this car has 56 miles on it

Inheritance

When a class inherits another class, it will automatically obtain all the attributes and methods of the other class. All classes are called parent classes, and the new class is called subclass. Simple example

>>> classParent():...     def hello(self):...print("Call the method of the parent class")...>>>classson(Parent):...     pass
...>>> a=son()>>> a.hello()
Call the method of the parent class

Complex example

>>> classelectric(Car):
 pass

>>> classmoto(Car):
 def __init__(self,shape):
  self.shape=shape
 def getshape():print('moto is '+ self.shape)>>> mycar=electric('china','ak','2010')>>> mycar.get_descriptive()
2010 akchina
>>> classmoto(Car):...     def __init__(self):...         pass
...>>> mycar=moto('china','ak','2010')Traceback(most recent call last):
 File "<stdin>", line 1,in<module>
TypeError:__init__() takes 1 positional argument but 4 were given

In this example, we see that an error was reported when defining moto, because the magic square init was rewritten inside, and the new init did not initialize the attributes of the parent class. The super function is needed to help python associate the parent class and subclasses, and rewrite as follows:

>>> classmoto(Car):...     def __init__(self,make,model,year):...super().__init__(make,model,year)...>>> my=moto('china','ak','2010')>>> my.get_descriptive()
2010 akchina

The attribute shape is added to the subclass, which corresponds to the method of adding getshape

>>> classmoto(Car):...     def __init__(self,make,model,year,shape):...super().__init__(make,model,year)...         self.shape=shape
...  def getshape(self):...print('moto is '+ self.shape)...>>> a =moto('cn','x','2020','sda')>>> a.getshape()
moto is sda

Import class

The class we wrote above is saved in a file named class.py, and annotation information can be added to the file. This saving method is to store the file in the module, and import the module when used from class import Car

You can also store multiple classes in a module, you can directly import the entire module, plus the period notation to call the classes needed in import class class.Car class.moto

Recommended Posts

Getting Started with Python-4: Classes and Objects
Getting started with Python(18)
Getting started with Python(9)
Getting started with Python(8)
Getting started with Python(4)
Getting started with Python (2)
Getting started with python-1
Getting started with Python(14)
Getting started with Python(7)
Getting started with Python(17)
Getting started with Python(15)
Getting started with Python(10)
Getting started with Python(11)
Getting started with Python(6)
Getting started with Python(3)
Getting started with Python(12)
Getting started with Python(5)
Getting started with Python (18+)
Getting started with Python(13)
Getting started with Python(16)
Getting started with python-2: functions and dictionaries
Getting started with Numpy in Python
04. Conditional Statements for Getting Started with Python
Getting started with Ubuntu
Getting started python learning steps
Played with stocks and learned Python
How to get started quickly with Python
Python and Go
How to read and write files with Python
Python introspection and reflection
python requests.get with header
Play WeChat with Python
[python] python2 and python3 under ubuntu
Web Scraping with Python
Python deconstruction and packaging
Python3 configuration and entry.md