25、python类的普通成员变量和私有成员变量

我们来演示下:
类的创建,成员变量,构造函数和析构函数,普通成员函数,访问私有成员变量。

print("Test Class")

class Video(object):
    # 4、私有成员变量 两个下划线开头定义的变量就是私有成员变量
    __name = "private name"
    # 3、直接声明成员变量
    # 声明的意思是这个变量的空间不产生,只有当Video生成对象的时候这个空间才产生,所以叫声明
    age = 20
    path = ""
    # 构造函数
    def __init__(self, path):
        print("Create Video")
        self.name = "public name"
        self.path = path
        print("path is", self.path)
    
    # Python约定了我们函数名全部是小写
    def get_name(self):
        return self.__name
    
    # 析构函数
    def __del__(self):
        print("Delete Video") 

# <class '__main__.Video'>   其中的这个__main__是入口模块名称
# 构造函数传递参数的方式,是在我们生成对象的时候直接传进去
video1 = Video("d:/video.mp4")
print(Video)

# 1、隐式的通过对象生成成员变量
video1.title = "title test"
print("title =", video1.title)
print(video1)
print(dir(video1))
print("end")

# 2、隐式的通过self生成成员变量
print("video1.name =", video1.name)

# 3、直接声明成员变量
print("video1.age =", video1.age)

# 私有成员变量无法直接访问
# print(video1.__name)
print("video1.get_name() =", video1.get_name())

程序输出:

Test Class
Create Video
path is d:/video.mp4
Delete Video
<class '__main__.Video'>
title = title test
<__main__.Video object at 0x000001E5ADF30A58>
['_Video__name', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'get_name', 'name', 'path', 'title']
end
video1.name = public name
video1.age = 20
video1.get_name() = private name

猜你喜欢

转载自blog.csdn.net/zhaopeng01zp/article/details/109289588