sonodan
sonodan

Reputation: 71

What is the technical term for this data in Python?

I am reviewing some code and looking at some of the classes. Within the class (for instance class ResourceBaseSchema), what is the technical term for the items id, private, canRead, canWrite, owner etc... I want to learn more about them, but I'm not sure what to search.

My experience so far with classes only covers attributes, which tends to be in the form of self.attribute.

Thanks

import json
from requests import Request
from pydantic import BaseModel
from pydoc import locate
from typing import List, Optional
import dataclasses
from dataclasses import dataclass
from datetime import datetime

SCHEMAS = {}

class ResourceBaseSchema(BaseModel):
    id: Optional[str]
    private: Optional[bool]
    canRead: Optional[List[str]]
    canWrite: Optional[List[str]]
    owner: Optional[str]
    anonymousComments: Optional[bool]
    comments: Optional[List[str]]
    createdAt: Optional[str]
    updatedAt: Optional[str]

Upvotes: 0

Views: 63

Answers (2)

wjandrea
wjandrea

Reputation: 32954

They are class attributes (AKA class variables), but more specifically, they're fields. See the Pydantic docs:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'Jane Doe'

User here is a model with two fields id which is an integer and is required, and name which is a string and is not required (it has a default value).

This is similar to dataclasses in the standard library:

The dataclass() decorator examines the class to find fields. A field is defined as class variable that has a type annotation.

Upvotes: 1

BeanBagTheCat
BeanBagTheCat

Reputation: 445

These are class attributes. They exist regardless of the objects created from the class. Attributes defined in the __init__ method, or in other methods, in the form self.attribute are object attributes. They exist only when an object is created from the class and they belong to that specific object.

In practical use you can access class attributes from a class reference that has not been instantiated like this:

class.attribute 

Notice that the class has not been instantiated i.e class()

Here's another example:

class test:
    class_attribute = 1
    
    def __init__(self):
        self.object_attribute = 2

# Accessing class attribute
a = test.class_attribute

# Accessing object attribute
b = test().object_attribute

self in python classes refers to the instance of the class. So it's only available upon instantiation.

Upvotes: 1

Related Questions