动态添加属性和方法
from types import MethodType
#创建一个猫类
class Cat():
__slots__ = ("name","age","weight","Run")
# 定义基本属性
def __init__(self,n):
self.name = n
# 定义猫的方法
def eat(self):
return "%s爱吃鱼"%self.name
# 实例化对象
c1 = Cat("tom")
# 在类外动态添加属性
c1.weight = 10
print(c1.weight)
# 在类外动态添加方法
def run(self):
print("%s能跑步"%self.name)
c1.Run = MethodType(run,c1)
c1.Run()
# 思考题:如果我们要限制实例的属性怎么办?
# 例如只允许给对象添加name,age,weight,Run属性
# 解决办法:定义类的时候,定义一个特殊的属性(__slots__),可以限制动态添加的属性
结果
10
tom能跑步
类的私有属性
_ private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self. _private_attrs。
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self
,且为第一个参数,self 代表的是类的实例。
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定使用 self。
类的私有方法
_ private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self. _private_methods。
class Person(object):
# publicName = 'tom' #公开变量
# __secretAge = 10 #私有变量
def __init__(self,n,a):
self.publicName = n #public
self.__secretAge = a #private
# 公开方法
def public(self):
print("这是公共方法")
#私有方法
def __private(self):
print("这是私有方法")
per = Person("tom",10)
per.public()
print(per.__secretAge)
per.__private()
结果
这是公共方法
Traceback (most recent call last):
File "D:\Maker Learn\PyCharm Community Edition 2020.2.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1448, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "D:\Maker Learn\PyCharm Community Edition 2020.2.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/LiuYuFeng/PycharmProjects/pythonProject/venv/python学习笔记/类私有属性.py", line 18, in <module>
print(per.__secretAge)
AttributeError: 'Person' object has no attribute '__secretAge'
Process finished with exit code -1
运算重载
class Number():
def __init__(self,a,b):
self.a = a
self.b = b
def __add__(self, other):
return Number(self.a+other.a,self.b+other.b)
def __str__(self):
return "(%d,%d)"%(self.a,self.b)
n1 = Number(1,2)
n2 = Number(4,5)
print(n1+n2)
结果
(5,7)