Twelfth lecture: Python classes and objects


1. Classes and objects

1. Data type
Different data types belong to different classes. Use built-in functions to view the data types
. 2. Objects
1, 2, 100 are all similar and different cases contained in the int class, and they are professionally called instances or objects
3. Everything in Python is an object

2. The creation of classes and objects

'''
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 attributes, class methods, static methods

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. Dynamically bind properties and methods

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()  #定义在类之外的,称为函数

Guess you like

Origin blog.csdn.net/buxiangquaa/article/details/114030627