Self-taught python-object-oriented

1 Object-oriented understanding

Process-oriented: write code from top to bottom according to business logic.
Object-oriented: classify and encapsulate functions to make development "faster, better, and stronger...

Example:
Zhang San is eating.
Facing the process
1 Zhang San feels hungry.
2 Wants to eat somewhere.
3 Waiting for the end of work time.
4 Waiting in line. . .
5 Choose dishes
6..
7.
8.. .

Object-oriented
Zhang San. Eat ()
Since object-oriented can make development "faster, better, and stronger..., how to do it, can it be achieved. The
steps are as follows:

#掌握一门面向的编程语言
	面向对象语言  python java  js   php   go

#要理解面向对象,必须先要理解 类和对象?
	类: 指的是类型
	对象: 指的是该类型下的具体哪一个

类和对象的关系
 类是对象的抽象,对象是类的具体
 类一个  对象多个
类的定义:具有相同属性和行为的一组对象的集合

举例:
张三是人类
李四是人类

对象: 张三  李四
类:  人类

#按照python定义类的语法 ,去定义类
	  语法 
		class 类名(父类):
			#定义属性
			属性的名=值
			
			#定义行为(方法)
			def 方法名(self,参数):
				#方法体
				
		  #定义人类
		  class people():
			#定义属性
			name="tom"
			age =22
	
			#定义行为
			def eat(self):
				print(people.name,"在吃饭。。")
		
# 创建对象
	#语法:
		  #对象名= 类名()
		  zhangshan=people()
	  
# 通过对象去调用行为
	   zhangshan.eat()

2 The difference between static attributes and instance attributes

 静态属性和实例属性
 静态属性属于类,实例属性属于对象
 class people():
	 #定义属性(静态属性)
	 name="李四"

    #构造方法__init__
    def __init__(self):
        self.age = 0  # 实例属性(对象)

    #定义行为
    def eat(self):
        print(people.name,self.age)

    def run(self):
        print(people.name,"在跑步。。")

#创建对象
zhangshan = people()

#通过对象调用属性
people.name="张三"
zhangshan.age=22
##通过对象调用行为
zhangshan.eat()
#创建对象
lishi = people()
lishi.age=32
##通过对象调用行为
lishi.eat()

3. The init method

构造方法,通过类创建对象时,自动触发执行 ,是个特殊方法
创建对象时,给属性赋值
  class people():

    #self当前对象

    #构造方法__init__
    #过类创建对象时,自动触发执行
    #创建对象时,给属性赋值
    def __init__(self,name,age):
        self.age = age  # 实例属性(对象)
        self.name=name

    def showinfo(self):
        print("名字:",self.name)
        print("年龄:",self.age)

#创建对象
zhangshan = people("张三",22)
zhangshan.showinfo()
print("-------------")
lishi = people("李四",32)
lishi.showinfo()

4.self current object

  class People():

    def __init__(self,name,age):
        self.name=name
        self.age=age

        def show(self):
        print(self.name,self.age)

	
p1 = People('张三',22)
p1.show()
 
p2 = People('张三2',12)
p2.show()
 
#当程序执行p1 = People('张三',22) self 就是 p1  
#当程序执行p2 = People('张三2',12)self 就是 p2

Guess you like

Origin blog.csdn.net/weixin_47580822/article/details/113726794