首页 > 解决方案 > 如何用两个类表示

问题描述

我一直在要求进行代码审查,我得到的答案是:

We're not in JavaScript - objects don't have to be dictionaries. This could be well-represented by a class for product, and a class for product size.

我一直在尝试联系但没有运气但是我确实设法通过聊天并得到了回复:

look at this - this is a size
  
"[EU 40](https://testing/shgz?pid=16002&tkn=3381a6fdc2bf2675b42e756c6dc668e5&ipa=87783)': 1,

@dataclass
class ProductSize:
name: str
link: str
quantity: int

* have a list of class instances
* in your ProductSize dataclass, make a @classmethod constructor that accepts a dictionary and returns a class instance

但是我的问题是我的知识还不足以理解这个问题以及这个人能够解决我的问题意味着什么。

目前我的代码是这样的:

import json
import re
from json.decoder import JSONDecodeError
from typing import ClassVar, List, Match, Optional

import attr
import requests
from selectolax.parser import HTMLParser

from config import configuration
from lib.utils import get, normalize_input


@attr.dataclass
class ProductPage:
    store: ClassVar[str] = "Shoezgallery"
    link: str = None
    name: Optional[str] = None
    price: Optional[str] = None
    image: Optional[str] = None
    pid: Optional[str] = None
    token: Optional[str] = None
    sizes: Optional[dict] = attr.ib(factory=dict)
    webhook: str = "mixed"
    delay: int = 0
    shortcut: List[str] = [
        '[Login](https://www.shoezgallery.com/en/authentification?back=my-account)',
        '[Cart](https://www.shoezgallery.com/en/commande)',
        '[Checkout](https://www.shoezgallery.com/en/authentification?back=https%3A%2F%2Fwww.shoezgallery.com%2Fen%2Fcommande%3Fstep%3D1&display_guest_checkout=1)',
    ]

    @staticmethod
    def get_sizes(doc: Optional[Match[str]], pid: Optional[str], token: Optional[str]) -> dict:

        try:
            data = json.loads(doc.group(1))

            return {
                f"[EU {get_sizes}](https://testing/shgz?pid={pid.attrs['value']}&tkn={token.attrs['value']}&ipa={att})": get(values, 'quantity')
                for att, values in data.items()
                if get(values, 'quantity') > 0
                for get_sizes in get(values, 'attributes_values').values()
            }
        except JSONDecodeError:
            return {}

    @classmethod
    def from_page(cls, link: str) -> "ProductPage":
        with requests.get(url=link) as response:
            if not response.ok:
                return cls(
                    link=link
                )

            doc = HTMLParser(response.text)

        name = doc.css_first('h1[itemprop="name"]')
        price = doc.css_first('span[itemprop="price"]')
        image = doc.css_first('img[itemprop="image"]')
        pid = doc.css_first('input[name="id_product"]')
        token = doc.css_first('input[name="token"]')
        sizes = re.search('var\s*combinationsFromController\s*=\s*(.*?);', response.text, re.M | re.S)

        return cls(
            link=link,
            name=name and name.text().strip(),
            price=price and price.text().strip().replace("'", ""),
            image=image and image.attributes.get('src'),
            sizes=sizes and cls.get_sizes(sizes, pid, token),
        )

    @property
    def payload(self) -> dict:
        return {
            "store": self.store,
            "link": self.link,
            "name": self.name or self.link.split("/")[-1],
            "price": self.price or "Not found",
            "image": self.image or "Not found",
            "sizes": self.sizes or {},
            "shortcut": self.shortcut,
            "webhook": self.webhook,
            "delay": self.delay
        }



if __name__ == '__main__':
    payload = ProductPage.from_page(link="https://www.shoezgallery.com/en/p16002-air-pegasus-83-nike-dj6892-001")

    print(payload)

我想知道我能做些什么来实现我有一个产品类和一个产品尺寸类?

标签: pythonpython-3.xclass

解决方案


您可以定义自己的类来表示自定义数据类型。您可以尝试阅读本指南

您要阅读的通用领域称为面向对象编程。我相信你会找到很多可以帮助你的话题。


推荐阅读