How to create a class attribute with predefined Python types?

Asked

Viewed 33 times

0

I consulted at documentation from Python, but I couldn’t find a syntax for how I could create an attribute from a class that has a predefined type.

I took as an example this exercise of W3schools:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

I think in case we have to restrict the entries that a user can give. For example, we wouldn’t want a user to put a string into action, or even leave that attribute null. How can we pre-determine the type of the class attribute?

  • 1

    For some reason, those who are learning to program now are confusing what is the data and the data top, especially in Python. These things are very different, but there must be some material that must be teaching wrong because it is not common for many people to make the same mistake and some time ago this did not happen. If you want to have types in the variables you should use a language that does this for real, Python has advantages in not doing this, even if it allows you to put a hint of what type will be the variable. But nothing guarantees that the given will be entered right.

1 answer

0

Starting from python 3.6 (if I’m not mistaken), it allows creating classes like this:

class Foo:
   nome: str
   idade: int
def __init__(self, nome: str, idade: int):
   self.nome = nome
   self.idade = idade

But if you want strong typing it is more recommended you use tools that offer it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.