一、类的定义
"""
格式一:
class 类名:
pass
格式二:
class 类名:
成员
pass
类命名规范: 大驼峰命名规则 FirstName
"""
# 类的第一种定义格式
class Student: #没有产生继承关系的情况下,类名()可写可不写
pass #空空如也
class Emp():
pass # 空空如也
# 类的第二种定义格式
# 类的定义 > 对象的创建 (类似于函数的调用)
# 学生 > 具体到哪个学生
class Student:
#成员
#成员变量
#成员方法
pass
""""
创建对象:
变量名 = 类名()
注意:
创建对象不限制数量
"""
# 对象的创建 > 函数的调用
stu1 =Student()
stu2 =Student()
# id() 函数用于获取对象的内存地址。
print(id(stu1),id(stu2))
二、类中的成员变量
'''
定义格式一:
class 类名:
def __init__(self): # 函数 > 方法
self.变量名1 = 值1
self.变量名2 = None
......
调用格式: 取值: 对象名.变量名
赋值: 对象名.变量名 = 值
变量名 = 值
self.变量名1 = 值1
'''
class Student:
def __init__(self): # 定义成员变量的方法名固定 __init__ 双下划线
self.name='mike' # 属性
self.pwd=None #属性不固定的情况下, 就可以给他一个None值,动态的数据
#创建对象
stu= Student()
#原来的值
print(stu.name,stu.pwd)
#给属性重新赋值
stu.name='samantha'
stu.pwd='aaa'
#输出结果
print(stu.name,stu.pwd)
'''
定义格式二: 如果一个的对象想拥有自己特定的属性,别的对象没有的.
对象名.变量名 = 值 > 实质就是一个变量的赋值
调用格式:
取值: 对象名.变量名
赋值: 对象名.变量名 = 值
'''
#创建对象1
stu1= Student()
#给属性重新赋值
stu1.name='samantha'
stu1.pwd='123'
#输出结果
print(stu1.name,stu1.pwd)
#发生异常:AttributeError: 'Student' object has no attribute 'tel'
#tel是对象2的属性,其他对象不能使用这个属性;
print(stu1.tel)
print('-'*100)
#创建对象2
stu2= Student()
#给属性重新赋值
stu2.name='john'
#创建对象2中特有的属性
stu2.tel=110
#输出结果
print(stu1.name,stu1.pwd,stu2.tel)