面向对象和类

#!/usr/bin/python
#-*-coding:utf-8 -*-
 
#!/usr/bin/python
#-*-coding:utf-8 -*-
 
# class 类名:
# '''文档注释'''
# 类体
#类 特征+技能 类是一系列对象的特征(变量)和技能(函数)的结合体
# class chinese:
# country='china'
# jiguan='haihai'
# def talk(self): #这个self 是要传入参数的 否则报错
# print('talking',self)
# # p=chinese()
# print(p)
#类 在定义节点 运行就会执行 不用专门执行
#类的两种用法
#1.属性的引用
#2.实例化
 
#1.属性的引用
# print(chinese.country) #china
# print(chinese.talk) #内存地址
# chinese.talk(123) ##类调用函数 就得传参数
# ##增加修改属性
# chinese.x=1
# print(chinese.x)
# chinese.country='jianada'
# print(chinese.country)
# print(chinese.jiguan)
# del chinese.jiguan #删除属性
# print(chinese.jiguan)
 
#2.实例化
#类() 就是类的实例化,得到的是一个具体的对象
# p1=chinese()
# print(p1)
# '''
# <__main__.chinese object at 0x000002528CD6D7F0>
# '''
 
'''
对象只有一种,就是属性引用
'''
# p1=chinese()
# print(p1)
# print(p1.country) #china
# p2=chinese()
# print(p2)
# print(p2.country) #china
#对象有共同的特征,也有各自不同的特征,以下是类里定义 共同特征 不同特征
#__init__
# class chinese:
# country='china'
# def __init__(self,name,age,sex,): #定义不同 name age sex
# self.Name=name #self.大小写都可以 p1.Name=name
# self.Age=age #p1.Age=age
# self.Sex=sex #p1.Sex=sex
# def talk(self):
# print('talkint',self.Name) #self.Name 可以看到具体是谁调用的
#
# # p1=chinese()
# print(p1)
'''
TypeError: __init__() missing 3 required positional arguments: 'name', 'age', and 'sex'
'''
'''
解释:
def __init__(self,name,age,sex,): 这里有4个参数 但是报错三个参数没有传
因为会把对象作为参数传给self
p1=chinese() 比如这个就会把p1作为参数传给self
# '''
# p1=chinese('agon','18','male')
# print(p1)
# print(p1.country)
# print(p1.Name)
# print(p1.Age)
# print(p1.talk()) #对象直接调用 又把自己作为参数传进去了
# # '''
# <__main__.chinese object at 0x000002BC683DD9B0>
# china
# agon
# 18
#
# '''
 
 
'''
类与对象的名称空间以及绑定方法
'''
class chinese:
country='china'
def __init__(self,name,age,sex,): #定义不同 name age sex
self.Name=name #self.大小写都可以 p1.Name=name
self.Age=age #p1.Age=age
self.Sex=sex #p1.Sex=sex
def talk(self):
print('talkint',self.Name) #self.Name 可以看到具体是谁调用的
 
p1=chinese('qiqi','22','male')
# print(p1)
p2=chinese('nini','22','male')
print(chinese.__dict__) #查看chinese的内置名称空间
'''
字典的格式
{'__module__': '__main__', 'country': 'china',
'__init__': <function chinese.__init__ at 0x00000257E4E9EF28>,
'talk': <function chinese.talk at 0x00000257E4EA3048>,
'__dict__': <attribute '__dict__' of 'chinese' objects>,
'__weakref__': <attribute '__weakref__' of 'chinese' objects>,
'__doc__': None}
 
'''
 
print(p1.__dict__)
'''
{'Name': 'qiqi', 'Age': '22', 'Sex': 'male'}
'''
 
print(p1.country) #先去自己的__dict__里找,没有再去类里找 再没有就没了
print(id(p1.country)) #查看id
print(id(p2.country)) #查看id
'''
id 一样 因为是共同的属性
1879109063152
1879109063152
'''
print(chinese.talk)
print(p1.talk) #查看id
print(p2.talk) #查看id
 
'''
长得并不一样
虽然是共同属性 但是talkself传入的是对象本身 对象不同 最后结果不同
<function chinese.talk at 0x000002C6104D3048>
<bound method chinese.talk of <__main__.chinese object at 0x000002C6104CD198>>
<bound method chinese.talk of <__main__.chinese object at 0x000002C6104CDAC8>>
'''
 
 
 
原文地址:https://www.cnblogs.com/lazyball/p/6977812.html