python学习记录day-12-类AND对象

类的创建

# 面向过程和面向对象--相辅相成
# 类和对象
# 类:相同/类似,属性元素的集合
# 一切皆对象
# 类的创建
class Student: # 类名,由一个或多个单词组成,每个单词首字母大写
pass
print(id(Student))
print(type(Student))
print(Student)

类的组成

# 类的创建
# 类的组成,类属性、实例方法、静态方法、类方法
class Student:
native_pace='吉林' # 直接写在类里的变量,称为类属性

# 类的初始化方法
def __init__(self,name,age):
self.name=name # self.name称为实例属性,进行了一个赋值操作,将局部变量的name赋值给实例属性
self.age=age
# 实例方法
def eat(self):
print('学生正在吃饭')
# 静态方法
@staticmethod
def method():
print('我使用了staticmethod进行修饰,所以是静态方法')
# 类方法
@classmethod
def cm(cls):
print('我使用了classmethod进行修饰,所以是静态方法')
# 类外定义的成为函数,类之内定义的称为方法
def drink():
print('喝水')

对象的创建

# 对象的创建 又称为类的实例化

# 创建Student类的对象
stu1=Student('张三',20) # 实例对象
print(id(stu1))
print(type(stu1))
print(stu1) # 对象的16进制内存地址
print('-----------------------')
print(id(Student))
print(type(Student))
print(Student) # 类的16进制内存地址

类的调用

实例方法调用

# 创建Student类的对象
stu1=Student('张三',20) # 实例对象
# 创建完成后调用
stu1.eat() # 对象.方法名()
print(stu1.name)
print(stu1.age)
# 另一种调用方法
print('--------------')
Student.eat(stu1) # 与前五行功能相等 # 类名.方法名(实例对象)

类属性调用

# 类属性的使用方法,所有对象共有
print(Student.native_pace)
stu1=Student('张三',45)
stu2=Student('李四',23)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace='天津'
print(stu1.native_pace)
print(stu2.native_pace)

类方法调用


print('--------类方法的使用方式---------')
Student.cm()

静态方法调用


print('--------静态方法的使用方式---------')
Student.method()

动态绑定属性和方法

# 动态绑定属性和方法
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print(self.name+'在吃饭')

stu1=Student('张三',20)
stu2=Student('李四',30)

动态绑定属性



# 为stu2动态绑定性别属性
stu2.gender='女'
# print(stu1.name,stu1.age,stu1.gender) # 性别报错
print(stu2.name,stu2.age,stu2.gender) # 性别输出成功
print('---------------')
stu1.eat()
stu2.eat()

动态绑定方法


def show():
print('定义在类之外,称为函数')
stu1.show=show() # 动态给stu1动态绑定
stu1.show()
# stu2.show() # 报错,原因是并没有为stu2绑定

学习链接

【花了2万多买的Python教程全套,现在分享给大家,入门到精通(Python全栈开发教程)】 https://www.bilibili.com/video/BV1wD4y1o7AS/?p=111&share_source=copy_web&vd_source=5f93c948050b4284ccf31ae9244fad4c

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哈哈哈哈去3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值