from dotenv import load_dotenv
import os
from googleapiclient.discovery import build
import json
load_dotenv()
class Channel:
"""Класс для ютуб-канала"""
youtube = build('youtube', 'v3', developerKey=os.getenv("API_YOU_TUBE"))
def __init__(self, channel_id: str) -> None:
"""Экземпляр инициализируется id канала. Дальше все данные будут подтягиваться по API."""
self.__channel_id = channel_id
self.title = self.get_data_init()["items"][0]["snippet"]["title"]
self.description = self.get_data_init()["items"][0]["snippet"]["description"]
self.url = "https://www.youtube.com/channel/" + self.get_data_init()["items"][0]["id"]
self.subscriber_count = self.get_data_init()["items"][0]["statistics"]["subscriberCount"]
self.video_count = self.get_data_init()["items"][0]["statistics"]["videoCount"]
self.view_count = self.get_data_init()["items"][0]["statistics"]["viewCount"]
def print_info(self) -> None:
"""Выводит в консоль информацию о канале."""
channel = self.youtube.channels().list(id=self.__channel_id, part='snippet,statistics').execute()
print(channel)
def get_data_init(self):
channel = self.youtube.channels().list(id=self.__channel_id, part='snippet,statistics').execute()
return channel
@staticmethod
def get_service():
return Channel.youtube
def to_json(self, data):
with open(data, "w") as f:
f.write(str(self.get_data_init()))
def __repr__(self):
return f"{self.__channel_id}, {self.subscriber_count}"
moscowpython = Channel('UC-OVMPlMA3-YCIeg4z5z23A')
moscowpython.__channel_id = 'Новое название'
print(moscowpython.__channel_id)
print(moscowpython)
# не выдает никаких ошибок, хотя должна AttributeError```
Изменено:
вот так выдает ошибку:
moscowpython = Channel('UC-OVMPlMA3-YCIeg4z5z23A')
print(moscowpython.__channel_id)
moscowpython.__channel_id = 'Новое название'
print(moscowpython.__channel_id)
print(moscowpython)
а вот так нет:
moscowpython = Channel('UC-OVMPlMA3-YCIeg4z5z23A')
# print(moscowpython.__channel_id)
moscowpython.__channel_id = 'Новое название'
print(moscowpython.__channel_id)
print(moscowpython)
让我们首先简化示例并删除所有不必要的内容:
结论:
Python中的dir()函数是一个内置函数,它返回对象的所有属性和方法的列表。
现在请注意第一个打印对象列表,特别是_Channel__channel_id,这是您的私有属性。
它也出现在第二个打印对象列表中,因此我们没有重新定义它,这可以使用test方法轻松检查。
在我们的示例中,该属性在Channel
__channel_id类中被定义为private。Python中的私有属性是使用一种名为name mangling的机制来处理的,该机制会重命名属性以防止它们被意外覆盖或在类外部访问。当您声明带有双下划线的属性时,Python会自动以
_ИмяКласса__ИмяАтрибута.在我们的例子中,__channel_id属性将被重命名为_Channel__channel_id。这样,如果您尝试更改 的值
moscowpython.__channel_id(如我们的示例中所示),Python不会抛出错误,因为它不会将其视为__channel_id私有属性。相反,它只是__channel_id在moscowpython对象中创建一个新属性,该属性将作为常规属性使用,但它不再是在类内部定义的属性,因为我们的属性已经看起来像这样 - _Channel__channel_id。您可以稍微扭曲一下这个想法,这样您就无法通过
__重写该类的魔术方法之一来创建属性:结论:
因此,这就是捕获错误的方法:
该错误与从类调用对象字段
AttributeError有关__channel_idChannel错误的:
正确的: