面向对象

1. 类的定义

经典类

class 类名

新式类

class 类名(父类名)

定义一个类:

class teacher(object):
  pass     #保障代码结构完整,用来占位

 

 

2. 类的实例化

● 创建一个类

class Student(object):
    # 定义方法
    def study(self):
        print('我在学习')

    def eat(self):
        print('我在吃饭')

 ● 类的实例化(创建对象)

对象名 = 类名()

s1 = Student()

 获取对象对应的类和所在的内存地址

print(s1)  # <__main__.Student object at 0x7f9be20848e0>

 获取对象的类型—创建对象所使用的类

print(type(s1))  # <class '__main__.Student'>

 调用方法

s1.study() # 我在学习
s1.eat()   # 我在吃饭

 

 3.self的作用

class Student(object):
    def study(self):
        # s1和self — 指向同一块内存空间,为同一个对象
        # 也就是说在对象调用方法时会将对象本身传入方法内部进行使用
        print(self)              
        print('我要学习')

    def eat(self):
        # self 有什么作用呢?
        # 可以在方法内部调用实例所拥有的属性或者方法
        print('我要吃饭')
        self.study()

 案例:

s1和self — 指向同一块内存空间,为同一个对象

s1 = Student()
print(s1) 
s1.study()
s1.eat()

 输出:

<__main__.Student object at 0x00000277FE31D370>
<__main__.Student object at 0x00000277FE31D370>
我要学习
我要吃饭
<__main__.Student object at 0x00000277FE31D370>
我要学习

 s2调用study()方法,和s1两个对象所指向不同的内存空间。

s2 = Student()       # <__main__.Student object at 0x00000277FE30FDF0>
s2.study()           # 我要学习

 

posted @ 2025-04-12 21:57  白森  阅读(10)  评论(0)    收藏  举报