python类和对象
1、定义
Python 是一种面向对象的编程语言。
Python 中的几乎所有东西都是对象,拥有属性和方法。
类:类是抽象的,一类实物的共性的体现,有共性的属性和行为
对象:具体化,实例化,有具体的属性值,有具体的行为
一个类对应N多个对象
类包含属性以及方法:
class 类名:
属性
方法
创建类 (class)
类名:符合标识符的规定但是一般是每个单词的首字母大写。(驼峰命名)
class Myclass:
i = 12345
def f(self):
return 'hello world'
x = Myclass() #实例化类
#访问类的属性和方法
print('属性:',x.i)
print('类的方法:',x.f())
#输出结果:
属性: 12345
类的方法: hello world
类有一个特殊方法(构造方法)init 该方法在类实例化时会自动调用
class Myclass:
def __init__(self,name,age):
self.name = name
self.age = age
a = Myclass('小明',18)
print(a.name)
print(a.age)
#输出结果
小明
18
类的方法
在类的内部,使用def关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数,self代表的是类的实例
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性的类外部无法直接进行访问
__weight = 0
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s说:%d岁"%(self.name,self.age))
#类实例化
p = people("小明",20,55)
p.speak()
#输出结果
小明说:20岁
类的属性与方法
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定是用 self。
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods。
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount) # 报错,实例不能访问私有变量
#输出结果
1
2
2
Traceback (most recent call last):
File "test.py", line 16, in <module>
print (counter.__secretCount) # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
类的私有方法实例:
class Site:
def __init__(self,name,url):
self.name =name
self.url = url
def who(self):
print("name:",self.name)
print('url:',self.url)
def __foo(self):
print('这是私有方法')
def foo(self):
print('这是共有方法')
self.__foo()
a = Site('A宁的博客地址','https://blog.csdn.net/weixin_49722764?spm=1000.2115.3001.5113')
a.who()
a.foo()
a.__foo()
#输出结果
name: A宁的博客地址
url: https://blog.csdn.net/weixin_49722764?spm=1000.2115.3001.5113
这是共有方法
这是私有方法
Traceback (most recent call last):
File "F:/peixun/new/pingshi.py", line 40, in <module>
a.__foo()
AttributeError: 'Site' object has no attribute '__foo'
#外部不能调用私有方法
类的专有方法:
- init : 构造函数,在生成对象时调用
- del : 析构函数,释放对象时使用
- repr : 打印,转换
- setitem : 按照索引赋值
- getitem: 按照索引获取值
- len: 获得长度
- cmp: 比较运算
- call: 函数调用
- add: 加运算
- sub: 减运算
- mul: 乘运算
- truediv: 除运算
- mod: 求余运算
- pow: 乘方