内容介绍
1、两大编程思想
2、类和对象的创建
3、类对象与类属性
4、类方法与静态方法
1、两大编程思想
2、类和对象的创建
类是多个类似事务组成的群体的统称。能够帮助我们快速理解和判断事务的性质
class Student: #Student为类的名称(类名)有一个或多个单词组成,每个单词的首字母大写,其余小写
native_place = '吉林' #直接写在类里的变量,称为类属性
#初始化方法
def __init__(self,name,age):
self.name=name #self.name 称为实体属性,进行一个赋值的操作将局部变量的那么值赋值给实体属性
self.age=age
#实例方法
def eat(self):
print('学生在吃饭')
#静态方法
@staticmethod
def method():
print('我使用了staticmethod,所以是静态方法')
#类方法
@classmethod
def cm(cls):
print('我是类方法,因为我使用classmethod进行修饰')
print(type(Student))
print(id(Student))
print(Student) #<class '__main__.Student'>
'''stu1为实例对象,用来调用类的属性和方法'''
stu1=Student('张三','20')
print(id(stu1))
print(type(stu1))
print(stu1)
print(stu1.native_place)
print(stu1.name)
print(stu1.age)
stu1.eat() #对象名+方法名()
Student.eat(stu1) #类名+方法名(类的对象)
stu1.method()
stu1.cm()
4、类属性、类方法与静态方法
print(Student.native_place)
stu1=Student('张三','20')
stu2=Student('李四','330')
print(stu1.native_place)
print(stu2.native_place)
Student.native_place='沈阳'
print(stu1.native_place)
print(stu2.native_place)
#类方法的使用方式
Student.cm()
Student.method()
class Student: #Student为类的名称(类名)有一个或多个单词组成,每个单词的首字母大写,其余小写
#初始化方法
def __init__(self,name,age):
self.name=name #self.name 称为实体属性,进行一个赋值的操作将局部变量的那么值赋值给实体属性
self.age=age
#实例方法
def eat(self):
print(self.name+'在吃饭'+self.age+'岁了')
#静态方法
@staticmethod
def method():
print('我使用了staticmethod,所以是静态方法')
#类方法
@classmethod
def cm(cls):
print('我是类方法,因为我使用classmethod进行修饰')
stu1=Student('张三','20')
stu2=Student('李四','30')
stu1.eat()
'''为stu2动态绑定型别属性'''
stu2.gender='女'
print(stu1.name,stu1.age)
print(stu2.name,stu2.age,stu2.gender)
stu2.eat()
#单独绑定方法
def show():
print('show your hands')
stu2.show=show
stu2.show()