初识python面向对象

时间:2023-03-09 04:06:11
初识python面向对象

一、初识python面向对象:

class Person: #使用class关键字定义一个类
  age=0 #类变量(静态变量)
  def eat(self,food): #定义一个方法
    self.age=5 #self是实例本身,self.age是实例变量
    print("I will eat %s" %food)

xiaofan=Person() #实例化,生成对象xiaofan
print(xiaofan.age) #调用对象方法,因为还没有调用eat方法,则使用类方法的值
xiaofan.eat("apple") #调用对象方法
print(xiaofan.age) #调用对象,此时调用了eat,则age的值改变了
print(Person.age) #调用类的方法

"""

0
I will eat apple
5
0

"""

#在python 的面向对象当中,类和实例以及实例和实例之间都是拥有独立的内存空间的.

#class 是我们定义类的关键字
#Person 是我们定义类的名称
#() 继承,如果没有继承对象,我们可以吧括号省略掉

#类是对事物的划分,我们使用的是类的实例
#所以我们调用类又叫做类的实例化
#在实例化的过程当中,括号的作用是传参
#类名加上括号就是实例化

二、

构造函数:(初始化函数 __init__)

class Person:
  def __init__(self,food):      #实例化时就被执行了
    self.age=0

    print("hello !!!")      

    print("I will eat %s" %food)          
  def eat(self,food):
    self.age=3
    print("I will eat %s" %food)

xiaofan=Person(milk)
print(xiaofan.age)
xiaofan.eat("rice")
print(xiaofan.age)

"""

hello !!!
I will eat milk
0
I will eat rice
3

#1、构造函数是指类实例化之后自动执行的
#2、构造函数传参需要在实例化的过程中在类的括号当中传
#3、构造函数必须没有返回值

"""

析构函数:实例被删除时执行

class Person:
  def __init__(self):
    print("hello world")
  def __del__(self):
    print("goodbye world")

xiaofan = Person()
del xiaofan

"""

hello world
goodbye world

"""

三、

#如果实例变量有定义,那么实例变量采用自己的值
#如果实例变量没有定义,那么采用类变量的值
#如果类变量也没有定义,那么报错
#但是实例变量无法对其他实例的实例变量产生影响
#也不能对类变量产生影响