Python中的面向对象编程(OOP)是一种编程范式,它使用对象和类的概念来组织代码。这种方法强调了数据的封装、继承和多态性,从而使代码更加模块化、灵活和可重用。Python是面向对象的高级动态编程语言,完全支持面向对象的基本功能,如封装,继承,多态,以及对基类方法的覆盖或重写。Python中对象的概念很广泛,Python中的一切内容都可以称为对象,函数也是对象。创建类时用的变量成员称之为对象特征数据成员,用函数形式表达对象行为的成员称之为成员的方法,数据成员和成员方法统称为类的成员。
来,很随我的脚步,边运行边操作边理解~~~!
一个class类的定义大致如下:
1.首行是class 开头,然后类名字+:号结尾 2.类的内部定义各种函数和变量; 3.函数内就封装各种功能。
class 类名字:
def __init__(self, 参数):
self.变量A=""
self.变量B=0
self.变量C=0.0
...代码
def 函数名字(self):
...代码
...代码
一个比较简单的类的定义如下所示:
class Tencent:
def __init__(self):
self.name = "腾讯"
if __name__ == '__main__':
t = Tencent();
print(t.name)
运行后就会得到打印:
学过Java的同学可能知道Java的私有成员函数是受保护的,外界无法进行操作,但是Python中是并没有对私有成员提供严格的访问保护机制的。私有成员一般都是在内部进行调用的,本来就是阻止外界调用的,但是Python有点例外,反而提供了调用私有成员的方式(非常不推荐大家这么做,因为确实不安全)。
在Python中私有成员是使用两个_来表示私有成员函数的,例如:
def __私有函数:
...
共有函数则是不带_号的:
def 共有函数:
...
实例:
class Tencent:
def __init__(self):
self.name = "腾讯"
def getName(self): # 公有方法
self.__display_name() #可以内部调用
return f"getName---> {self.name}."
def __display_name(self): # 私有方法
print(f"getName---> {self.name}.")
if __name__ == '__main__':
t = Tencent();
print("1->",t.name)
print("2->",t.getName())
# print("3->",t.__display_name()) #会报错
执行完毕将会打印:
1-> 腾讯
getName---> 腾讯.
2-> getName---> 腾讯.
如果print("3->",t.__display_name()) 这一行代码打开会报错:
1-> 腾讯
getName---> 腾讯.
2-> getName---> 腾讯.
Traceback (most recent call last):
File "/media/zhenghui/soft/project/pyProject/py_01/test.py", line 17, in <module>
print("3->",t.__display_name()) #会报错
AttributeError: 'Tencent' object has no attribute '__display_name'
使用智能的IDE可以看到是无法找到t.__display_name()函数的
点击后也是无法跳转的:
这就是共有和私有的区别。
私有函数可以在内部函数中调用,例如本实例使用的getName()中调用了
_ _display_name();
数据成员的作用是用来说明对象特有的一些属性,例如一个学生,那么学生都包含什么?学生的信息有:学号,身份证号,名字,学院名称,班级,学分等等。例如书的名字,作者,出版社,出版日期,价格等等都属于数据成员。
Python中类的数据成员是可以动态添加的,这个特点是Python动态类型的一种比较好的体现。
在init中初始化的成员属于对象的数据成员
例如下面这个代码:
class Student:
def __init__(self):
# 学生名字
self.name = "吴霸哥" # 这种属于对象的数据成员
if __name__ == '__main__':
st = Student();
print("学生名字->",st.name)
运行后会得到:
学生名字-> 吴霸哥
当然了,也可以传递过去参数:
class Student:
def __init__(self,_name):
# 学生名字
self.name = _name # 这种属于对象的数据成员
if __name__ == '__main__':
st = Student("吴霸哥");
print("学生名字->",st.name)
运行后会得到:
学生名字-> 吴霸哥
在init函数外,在class内定义的成员属于类的数据成员。
class Student:
type = "student" # 这种属于类的数据成员
def __init__(self,_name):
# 学生名字
self.name = _name # 这种属于对象的数据成员
print(self.type)
if __name__ == '__main__':
st = Student("吴霸哥");
print("学生名字->",st.name)
运行后会得到:
student
学生名字-> 吴霸哥
class Student:
type = "student" # 这种属于类的数据成员
def __init__(self,_name):
# 学生名字
self.name = _name # 这种属于对象的数据成员
print(self.type)
if __name__ == '__main__':
st = Student("吴霸哥");
print("修改前:")
print("学生名字->",st.name)
print("#######################")
st.name = "游霸哥"
print("修改后")
print("学生名字->",st.name)
运行结果:
student
修改前:
学生名字-> 吴霸哥
#######################
修改后
学生名字-> 游霸哥
你可以思考下,在添加前我为什么使用了try{},这个留给你思考了。可以把思考的结果评论下。
class Student:
type = "student" # 这种属于类的数据成员
def __init__(self,_name):
# 学生名字
self.name = _name # 这种属于对象的数据成员
print(self.type)
if __name__ == '__main__':
st = Student("吴霸哥");
print("修改前:")
print("学生名字->",st.name)
print("#######################")
st.name = "游霸哥"
print("修改后")
print("学生名字->",st.name)
print("#######################")
print("添加年龄前")
try:
print("学生年龄->",st.age)
except Exception:
print("学生年龄->","null")
print("#######################")
print("添加年龄后")
st.age = 18
try:
print("学生年龄->",st.age)
except Exception:
print("学生年龄->","null")
运行结果:
student
修改前:
学生名字-> 吴霸哥
#######################
修改后
学生名字-> 游霸哥
#######################
添加年龄前
学生年龄-> null
#######################
添加年龄后
学生年龄-> 18
Process finished with exit code 0
学过Java和C++的童鞋可能都知道Java或C++都可以定义private和public的函数,那么Python也是可以的。
在Python中可以大概分为四种:公有方法、私有方法、类方法、静态方法。
例子:
def public_method(self):
print("这是一个公有方法")
例子:
def __private_method(self):
print("这是一个私有方法")
例子:
@classmethod
def class_method(cls):
print("这是一个类方法")
例子:
@staticmethod
def static_method():
print("这是一个静态方法")
class MyClass:
def public_method(self):
print("这是一个公有方法")
def __private_method(self):
print("这是一个私有方法")
@classmethod
def class_method(cls):
print("这是一个类方法")
@staticmethod
def static_method():
print("这是一个静态方法")
if __name__ == '__main__':
try:
MyClass.static_method()
except Exception:
print("MyClass.static_method() 调用失败")
try:
MyClass.class_method()
except Exception:
print("MyClass.class_method() 调用失败")
try:
MyClass.public_method()
except Exception:
print("MyClass.public_method() 调用失败")
try:
MyClass.__private_method()
except Exception:
print("MyClass.__private_method() 调用失败")
为了防止报错阻挡其他的打印,这里依然用到了try代码块。
运行后结果:
这是一个静态方法
这是一个类方法
MyClass.public_method() 调用失败
MyClass.__private_method() 调用失败
可以看到 public_method 和 __private_method方法都调用失败了。
换一种调用public_method的方式:
class MyClass:
def public_method(self):
print("这是一个公有方法")
def __private_method(self):
print("这是一个私有方法")
@classmethod
def class_method(cls):
print("这是一个类方法")
@staticmethod
def static_method():
print("这是一个静态方法")
if __name__ == '__main__':
try:
MyClass.static_method()
except Exception:
print("MyClass.static_method() 调用失败")
try:
MyClass.class_method()
except Exception:
print("MyClass.class_method() 调用失败")
try:
myc = MyClass()
myc.public_method()
except Exception:
print("MyClass.public_method() 调用失败")
try:
MyClass.__private_method()
except Exception:
print("MyClass.__private_method() 调用失败")
结果:
这是一个静态方法
这是一个类方法
这是一个公有方法
MyClass.__private_method() 调用失败
但是__private_method是私有的函数只能在class类的内部中的函数中调用,修改如下:
class MyClass:
def public_method(self):
print("这是一个公有方法")
self.__private_method()
def __private_method(self):
print("这是一个私有方法")
@classmethod
def class_method(cls):
print("这是一个类方法")
@staticmethod
def static_method():
print("这是一个静态方法")
if __name__ == '__main__':
try:
MyClass.static_method()
except Exception:
print("MyClass.static_method() 调用失败")
try:
MyClass.class_method()
except Exception:
print("MyClass.class_method() 调用失败")
try:
myc = MyClass()
myc.public_method()
except Exception:
print("MyClass.public_method() 调用失败")
try:
MyClass.__private_method()
except Exception:
print("MyClass.__private_method() 调用失败")
执行结果:
这是一个静态方法
这是一个类方法
这是一个公有方法
这是一个私有方法
MyClass.__private_method() 调用失败
实例属性:
__init__
中定义,并通过 self
关键字与特定实例相关联。class MyClass:
def __init__(self, value):
self.instance_attribute = value
类属性:
class MyClass:
class_attribute = "这是一个类属性"
# 所有MyClass的实例将共享class_attribute
公有属性:
class MyClass:
def __init__(self):
self.public_attribute = "这是一个公有属性"
私有属性(Private Attributes):
__
开头的属性被视为私有属性。class MyClass:
def __init__(self):
self.__private_attribute = "这是一个私有属性"
受保护的属性:
_
开头的属性被视为受保护的。class MyClass:
def __init__(self):
self._protected_attribute = "这是一个受保护的属性"
属性装饰器(Property Decorators):
@property
装饰器可以将方法变为属性调用。class MyClass:
def __init__(self):
self._attribute = None
@property
def attribute(self):
return self._attribute
@attribute.setter
def attribute(self, value):
self._attribute = value
@attribute.deleter
def attribute(self):
del self._attribute
全代码演示:
class MyClass:
class_attribute = "这是一个类属性" # 类属性
def __init__(self, value):
self.instance_attribute = value # 实例属性
self.public_attribute = "这是一个公有属性"
self.__private_attribute = "这是一个私有属性"
self._protected_attribute = "这是一个受保护的属性"
self._attribute = None
@property
def attribute(self):
return self._attribute
@attribute.setter
def attribute(self, value):
self._attribute = value
@attribute.deleter
def attribute(self):
del self._attribute
if __name__ == '__main__':
print("############# 第一种:直接调用演示 ######################")
try:
print("MyClass.class_attribute=",MyClass.class_attribute)
except Exception:
print("MyClass.class_attribute() 调用失败")
try:
print("MyClass.instance_attribute=",MyClass.instance_attribute)
except Exception:
print("MyClass.instance_attribute() 调用失败")
try:
print("MyClass.public_attribute=",MyClass.public_attribute)
except Exception:
print("MyClass.public_attribute() 调用失败")
try:
print("MyClass.__private_attribute=",MyClass.__private_attribute)
except Exception:
print("MyClass.__private_attribute() 调用失败")
try:
print("MyClass._protected_attribute=",MyClass._protected_attribute)
except Exception:
print("MyClass._protected_attribute() 调用失败")
print("############# 第二种:实例化后调用 ######################")
myc = MyClass("aaa") #实例化对象
try:
print("myc.class_attribute=",myc.class_attribute)
except Exception:
print("myc.class_attribute() 调用失败")
try:
print("myc.instance_attribute=",myc.instance_attribute)
except Exception:
print("myc.instance_attribute() 调用失败")
try:
print("myc.public_attribute=",myc.public_attribute)
except Exception:
print("myc.public_attribute() 调用失败")
try:
print("myc.__private_attribute=",myc.__private_attribute)
except Exception:
print("myc.__private_attribute() 调用失败")
try:
print("myc._protected_attribute=",myc._protected_attribute)
except Exception:
print("myc._protected_attribute() 调用失败")
结果很客观:
############# 第一种:直接调用演示 ######################
MyClass.class_attribute= 这是一个类属性
MyClass.instance_attribute() 调用失败
MyClass.public_attribute() 调用失败
MyClass.__private_attribute() 调用失败
MyClass._protected_attribute() 调用失败
############# 第二种:实例化后调用 ######################
myc.class_attribute= 这是一个类属性
myc.instance_attribute= aaa
myc.public_attribute= 这是一个公有属性
myc.__private_attribute() 调用失败
myc._protected_attribute= 这是一个受保护的属性
Process finished with exit code 0
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。