1、类与对象
1.数据类型
不同的数据类型属于不同的类,使用内置函数查看数据类型
2.对象
1,2,100都是int类下包含的相似的不同个例,专业属于称之为实例或者对象
3.Python中一切皆对象
2、类与对象的创建
'''
class Student: #Student为类名,每个单词的首字母大写,其余小写
pass
print(id(Student),type(Student),Student) #2176184380768 <class 'type'> <class '__main__.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('类方法')
#创建Student类的对象
stu1=Student('张三',20)
stu1.eat() #吃饭饭
print(stu1.age)
print(stu1.name)
Student.eat(stu1) #吃饭饭
4、类属性、类方法、静态方法
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('类方法')
#类属性的使用方式
print(Student.native_pace) #湖北
stu1=Student('一',1)
stu2=Student('二',2)
print(stu1.native_pace)#湖北
print(stu2.native_pace)#湖北
Student.native_pace='湖南'
print(stu1.native_pace)#湖南
print(stu2.native_pace)#湖南
#类方法使用
Student.cm() #类方法
#静态方法
Student.method() #使用了staticmethod,所有是静态方法
5、动态绑定属性和方法
class Student:
def __init__(self,name,age):
self.name=name # self.name为实体属性,进行了一个赋值操作,将局部变量的name赋值给实体属性
self.age=age
# 实例方法
def study(self):
print(self.name+'今年'+str(self.age)+'岁'+'在学习')
stu1=Student('张三',20)
stu2=Student('李四',21)
stu1.study() #张三今年20岁在学习
#一个Student类可以创建多个类的实例对象,每个实例对象的属性不同
#为stu1动态绑定性别属性
stu2.gender='女'
print(stu1.name,stu1.age) #张三 20
print(stu2.name,stu2.age,stu2.gender) #李四 21 女
def show():
print('定义在类之外的,称为函数')
stu1.show=show
stu1.show() #定义在类之外的,称为函数