简体   繁体   English

创建类的实例时如何限制可能的输入。 例如,仅创建类的整数实例

[英]How to restrict the possible inputs when creating an instance of a class. For e.g. only creating integer instances of a class

In Python OOP is it possible to restrict the input when creating an object.在 Python OOP 中,可以在创建对象时限制输入。

For eg if I only wanted int objects for a class.例如,如果我只想要一个类的 int 对象。 So if a string was entered it would return an error.因此,如果输入字符串,它将返回错误。

My initial thought was to write an if statement in the init method that would return an error msg if the conditions were not met.我最初的想法是在 init 方法中编写一个 if 语句,如果不满足条件,它将返回错误 msg。

The only problem with the above is that it seems that returning a statement in an init method is far from ideal.上述唯一的问题是,在 init 方法中返回语句似乎远非理想。

Any guidance would be much appreciated任何指导将不胜感激

You can use type suggestions in the method header.您可以在方法标题中使用类型建议。 This is considered better practices than forcing.这被认为是比强制更好的做法。

def __init__(name: str) -> str:
    return "Hello, " + name

If you did need to force you can add isinstance(variable, type) like this.如果你确实需要强制你可以像这样添加 isinstance(variable, type) 。

if not isinstance(name, str):
    raise TypeError

The basic way you would implement this is to add a check to your __init__ method that raises an error (usually a TypeError ) if an incorrect type is passed into the method.实现这一点的基本方法是向__init__方法添加一个检查,如果将不正确的类型传递给方法,则会引发错误(通常是TypeError )。 You would also want to hint to your readers about the parameters expected type using function annotations .您还需要使用函数注释向读者提示有关参数预期类型的​​信息。 In practice though, it is generally better to try and convert whatever was passed into the __init__ method into the type that you expect.但在实践中,通常最好尝试传入__init__方法的任何内容转换为您期望的类型。 Python is flexible, and using that flexibility to your advantage is beneficial for you in designing and building your application, as well as for anyone who potentially may want to utilize your code down the line. Python 是灵活的,利用这种灵活性的优势对您设计和构建应用程序以及任何可能想要直接使用您的代码的人都有好处。

An example:一个例子:

class Test:
    def __init__(self, param: int):
        self.my_param = int(param)

In the above example, if you were to wrap your param with an exception, the entire application would crash if the exception was left unhandled.在上面的例子中,如果你用一个异常来包装你的param ,如果这个异常没有得到处理,整个应用程序就会崩溃。 If you add the int() conversion, it will instead try to convert whatever is passed into an int , thereby saving your application from a crash as long as the passed item can be converted.如果您添加int()转换,它将尝试将传递的任何内容转换为int ,从而只要可以转换传递的项目,就可以使您的应用程序免于崩溃。 There are cases where you would absolutely want to specify an exact type to be passed, but flexibility is usually more important.在某些情况下,您绝对希望指定要传递的确切类型,但灵活性通常更为重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何对返回相同类型的类实例的两个类实例(以float作为子类)执行算术运算? 例如Speed(2)+ Speed(2) - How to perform arithmetic on two class instances (with float as a subclass) which return a class instance of the same type? e.g. Speed(2) + Speed(2) 使用类实例名称作为图例条目,例如绘图 - Use class instance names as legend entry for e.g. a plot 如何在类实例上正确执行算术? 例如,将House类实例的列表的n_people属性求和 - How to correctly perform arithmetic on classes instances? E.g. Sum the n_people attribute for a list of House class instances 当变量应该设置为私有类变量(例如_var)vs类常量(例如VAR)vs私有类常量(例如_VAR)? - When a variable should be set as a private class variable (e.g. _var) vs a class constant (e.g. VAR) vs a private class constant (e.g. _VAR)? 创建类实例 - Creating class instances 自动创建类的实例 - Auto creating instances of class 创建类实例列表 - Creating a list of class instances 创建一个没有实例的 static class - Creating a static class with no instances Django:如何访问以前的 model class 实例,同时创建相同 ZA2F2ED4F8EBC2CBB14C21A2DZ 实例的新实例 - Django: How to access the previous model class instances while creating new instance of the same class? 在 PySimpleGUI 中创建 window 布局时出现错误“您的行不是可迭代的(例如列表)” - Error "Your row is not an iterable (e.g. a list)" when creating window layout in PySimpleGUI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM