概念:类即类别、种类,是面向对象设计最重要的概念,对象是特征与技能的结合体,而类则是一系列对象相似的特征与技能的结合体
在现实世界中:先有对象,再有类
在程序中:务必保证先定义类,后产生对象
【1】类的创建
class 类名: 属性 方法
【2】如何知道类中的属性和方法
1、使用dir()内置函数
class MyClass: name = 'myclass' def showClassName(self): print(MyClass.name) #查看类有哪些属性和方法 print(dir(MyClass)) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'showClassName']
2、通过访问类的字典属性__dict__
class MyClass: name = 'myclass' def showClassName(self): print(MyClass.name) #查看类有哪些属性和方法 print(MyClass.__dict__) {'__doc__': None, 'showClassName': <function MyClass.showClassName at 0x10471b510>, '__module__': 'test1', 'name': 'myclass', '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__dict__': <attribute '__dict__' of 'MyClass' objects>}
class MyClass: #文档字符串 'this is MyClass' name = 'myclass' def showClassName(self): print(MyClass.name) #类MyClass的名字(字符串) print(MyClass.__name__) #MyClass #类MyClass的文档字符串 print(MyClass.__doc__) #this is MyClass #类MyClass的所有父类构成的元组 print(MyClass.__bases__) #(<class 'object'>,) #类MyClass的属性 print(MyClass.__dict__) #{'__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': 'this is MyClass', 'name': 'myclass', '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__module__': 'test1', 'showClassName': <function MyClass.showClassName at 0x10471b598>} #类MyClass定义所在的模块 print(MyClass.__module__) #test1 #实例MyClass对应的类 print(MyClass.__class__) #<class 'type'>
【3】属性查找
类有两种属性:数据属性和函数属性
1、类的数据属性是所有对象共享的,id都一样
class Student: school = "YD" def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def say(self): print(self.name) s1 = Student("张三",18,"男") s2 = Student("李四",20,"女") s3 = Student("王五",28,"男") print(id(Student.school)) print(id(s1.school)) print(id(s2.school)) print(id(s3.school)) ''' 4369544728 4369544728 4369544728 4369544728 '''
2、类的函数属性是绑定给对象用的
#类的函数属性是绑定给对象使用的,obj.method称为绑定方法,内存地址都不一样 #id是python的实现机制,并不能真实反映内存地址,如果有内存地址,还是以内存地址为准 class Student: school = "YD" def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def say(self): print(self.name) s1 = Student("张三",18,"男") s2 = Student("李四",20,"女") s3 = Student("王五",28,"男") print(Student.say) print(s1.say) print(s2.say) print(s3.say) ''' <function Student.say at 0x10471b598> <bound method Student.say of <test1.Student object at 0x10471f828>> <bound method Student.say of <test1.Student object at 0x10471f860>> <bound method Student.say of <test1.Student object at 0x10471f898>> '''
注意:在obj.name会先从obj自己的名称空间里找name,找不到则去类中找,类也找不到就找父类...最后都找不到就抛出异常