类与对象:
先定义类,然后产生对象
class People(object):
def watch(self):
print("watch")
print(People.__dict__)
##dict属性:(类的变量名和函数名,这种类的属性是定义类完成后就有的,还有其他的一些信息)
#{'__module__': '__main__', 'watch': <function People.watch at 0x000001B53D76C7B8>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
zym = People()
zym.watch()
__init__属性:
构造属性用的,他可以给对象定制自己独有的特征
class People(object): def __init__(self,name,age): self.name = name self.age = age def watch(self): print("watch") print(People.__dict__) ##dict属性:(类的变量名和函数名,还有其他的一些信息) #{'__module__': '__main__', 'watch': <function People.watch at 0x000001B53D76C7B8>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None} zym = People("zym",18) zym.watch() print(zym.name) #zym print(zym.age) #18 print(zym.__dict__) #这个是实例变量属性的字典 #{'name': 'zym', 'age': 18}
注意事项:
__init__中可以后任意的python代码
但是一定不能有返回值
类的特殊属性:
#python为类内置的特殊属性
类名.__name__# 类的名字(字符串)
类名.__doc__# 类的文档字符串
类名.__base__# 类的第一个父类
类名.__bases__# 类所有父类构成的元组
类名.__dict__# 类的字典属性
类名.__module__# 类定义所在的模块
类名.__class__# 实例对应的类(仅新式类中)
class People(object): def __init__(self,name,age): self.name = name self.age = age def watch(self): print("watch") print(People.__dict__) #{'__module__': '__main__', '__init__': <function People.__init__ at 0x000001CE83F8C7B8>, # 'watch': <function People.watch at 0x000001CE85001048>, '__ # dict__': <attribute '__dict__' of 'People' objects>, # '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None} print(People.__doc__) #None print(People.__base__) #<class 'object'> print(People.__bases__) #(<class 'object'>,) print(People.__module__) #__main__ print(People.__class__) #<class 'type'> print(People.__name__) #People
类的两种属性:
数据属性:
是所有对象共享的属性
类函数属性:
类的函数属性是绑定给对象使用的,obj.xxxx(),进行调用
self的意义:
class People(object): def __init__(self,name,age): self.name = name self.age = age def watch(self): print("watch") print(self) #下面直接用类来调用类的函数属性,需要传入一个self值,传入他自己就是类本身 People.watch(People) #watch #<class '__main__.People'> #下面用实例属性调用函数属性 zym = People("zym",18) zym.watch() #<__main__.People object at 0x00000130C33836D8>
对象之间的交互:
class People(object): def __init__(self,name,age): self.name = name self.age = age def watch(self,movie): print("%s is watching %s"%(self.name,movie.name)) class Movies(object): def __init__(self,name): self.name = name zym = People("zym",18) Tatinic = Movies("Tatinic") zym.watch(Tatinic)
类的继承和派生: