Answer the question
In order to leave comments, you need to log in
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())
Answer the question
In order to leave comments, you need to log in
class Math:
def __init__(self, first, second=""):
if isinstance(first, Int) and isinstance(second, Int):
self.first = first
self.second = second
class Math:
def __init__(self, first, second=""):
print(type(first)) # <class '__main__.Int'>
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):
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question