R
R
Reikoni2021-06-06 15:07:36
Python
Reikoni, 2021-06-06 15:07:36

How to understand that an attribute is a specific class in Python?

Hello. Understanding OOP in Python. And I decided to make something like a calculator using classes.
Here is the code:

class Object:
    def __init__(self, type, info):
        self.type = type
        self.info = info
    def Get(self, what):
        if what == "type":
             return self.type
        elif what == "info":
             return self.info
class Int(Object):
     def __init__(self, info):
          Object.type = "int"
          Object.info = info

class Math:
    def __init__(self, first, second=""):
        #тут надо понять программе, что атрибуты first и second являются классами Int (не базовому int, а моему классу Int).
    def sum(self):
        return int(self.first) + int(self.second)

i1 = Int("8")
i2 = Int("2")
m = Math(i1, i2)
print(m.sum())

As you understand, the Math class needs to understand that the attributes first and second are instances of the Int class, and when it understands this, get the numbers 8 and 2 from it and print their sum

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sswwssww, 2021-06-06
@ifullut

class Math:
    def __init__(self, first, second=""):
        if isinstance(first, Int) and isinstance(second, Int):
            self.first = first
            self.second = second

S
soremix, 2021-06-06
@SoreMix

class Math:
    def __init__(self, first, second=""):
        print(type(first)) # <class '__main__.Int'>

He perfectly understands what class the variable belongs to

V
Vindicar, 2021-06-06
@Vindicar

In general, dynamic typing is adopted in python - in other words, if a class has the necessary properties and methods, then it does not matter what class it really is.
But if you really need it, then there are ways.
1. Dynamic class check when executing
isinstance(x, list) will check that the object is a list or inherits from a list.
isinstance(x, (list, tuple)) will do the same for a couple of possible classes.
I would not recommend this approach, since the check is performed every time it is executed, even if its result is known. Also, it's not uncommon for a method to be labeled as "expecting a list", but all it does with the list is iterate over the elements. Those. in fact, any collection would have worked.
2. Static checking (google about python type hints)
You rewrite the method header like this:

from typing import Optional
class Math:
    def __init__(self, first: Int, second: Optional[Int] = None):

If you then pass the wrong types to the constructor, the python interpreter itself will ignore this and execute the script as usual. But there is a separate mypy utility that statically (without running the script) analyzes the script and checks what you pass to a particular method, and will throw an error if the type is incorrect. In this way, you can statically verify the correctness of the script without losing performance at run time.
3. Protocols
This is a development of the previous approach, similar to interfaces in other OOP languages. They are also shared with mypy, they are ignored by the python interpreter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question