编程思想:1.面向对象 2.面向过程
类对象:1.类属性 2.类方法 3.实例方法 4.静态方法
实例对象: 1.类名() 创建实例对象c 2.动态绑定属性 3.动态绑定方法
print(id(Student))
print(type(Student))
print(Student)
# 5805061296
# <class 'type'>
# <class '__main__.Student'>
class Student:
native_place = '吉林'
def __init__(self, name, age):
self.name = name # 实例属性 进行赋值
self.age = age
# 实例方法
def eat(self):
print('学生在吃饭')
# 静态方法
@staticmethod
def method():
print('静态方法')
# 类方法
@classmethod
def cm(cls):
print('类方法')
# 在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')
# 创建Student类的对象
stu1 = Student('张三', 20) # 实例对象
print(id(stu1))
print(type(stu1))
print(stu1)
print('------------------')
print(id(Student)) # 类对象
print(type(Student))
print(Student)
stu1.eat()
print(stu1.name)
print(stu1.age)
print('-------------')
Student.eat(stu1) # stu1.eat() 一样
# 类名.方法名
# 类属性的使用方式
print(Student.native_place)
stu1 = Student('张三', 20)
stu2 = Student('李四', 30)
print(stu1.native_place)
print(stu2.native_place)
Student.native_place = '天津'
print(stu1.native_place)
print(stu2.native_place)
print('-----------类方法的使用方式--------------')
Student.cm() # 类方法
Student.method() # 静态方法
''' 动态绑定属性和方法'''
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(self.name + '在吃饭')
stu1 = Student('李四', 30)
stu2 = Student('张三', 20)
print(id(stu1))
print(id(stu2))
print('-------为stu2动态绑定性别属性----------')
# 动态添加属性
stu2.gender = '女'
print(stu1.name, stu2.age)
print(stu2.name, stu2.age, stu2.gender)
print('-------------------')
stu1.eat()
stu2.eat()
def show():
print('定义在类之外的方法')
stu1.show = show
stu1.show()
# stu2.show() # 并没有绑定show方法
python 类与对象
最新推荐文章于 2024-07-27 12:20:46 发布