类方法来创建新实例

编程入门 行业动态 更新时间:2024-10-23 17:36:31
本文介绍了类方法来创建新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我遇到了一些严重的OOP与Python和我遇到了一些问题。 我有一个类带有一个初始化器,三个私有变量以及为每个变量设置和获取方法。

I am getting into some serious OOP with Python and am running into some issues. I have a class with an initialiser, three private variables and set and get methods for each variable.

此外,它有一个输入法,在调用这些变量时输入一个值,而不需要在主函数中调用一个输入,将值传递给类集set方法。这样我可以立即验证特定于数据需求的方法中的用户条目:

Additionally, it has an input method that lets the user enter a value for the variables when they are called, rather than requiring an input call in the main function that passes a value to the class set method. This way I can immediately validate the user entry within the method specific to the data requirements:

def input_first_name(self): done = 0 while done == 0: print("Input First Name:",end='') first_name = input() if first_name.isalpha(): self.__first_name = first_name done = 1 else: print("Invalid Entry. Please use alphabetic characters only.")

使用这些输入法,我有另一个方法使用它们来创建一个新的类实例知道你在想什么):

Using these input methods, I have another method that uses them to create a new class instance (just wait, I already know what you're thinking):

@classmethod def new(cls): cls.input_first_name(cls) cls.input_last_name(cls) cls.input_birthday(cls) return cls

所以我知道使用这个,我不会实际上实例化一个新的实例。但是,使用方法不会立即引发任何错误。但是当我使用get方法引用我新创建的实例时,这就是我遇到的麻烦,我知道是不实例化。

So I know that using this, I won't have actually instantiated a new instance. However, using the methods doesn't immediately throw any errors. But when I refer to my newly created instance with the get method, that's where I get into trouble that I know is related to not instantiating.

new_relative = Relative.new() print(new_relative.get_first_name())

导致:

TypeError: get_first_name() missing 1 required positional argument: 'self'

有一种方法可以在我的main函数中使用一个类方法来实例化一个使用我的想法的新实例

Is there away to a way to have a class method usable in my main function for instantiating a new instance that employs my idea of user input and validation in a simple and elegant manner?

作为参考,该类的最小示例:

For reference, a minimal sample of the class:

class Relative: __first_name = "" __last_name = "" __birthday = 0 def __init__(self, first_name,last_name,birthday): self.__first_name = first_name self.__last_name = last_name self.__birthday = birthday def get_first_name(self): return self.__first_name

推荐答案

属性(Pythonic替换无尽的 get s和设置 Python @property与getter和setter ),并且只保留输入到类方法。这里是一个最小的例子:

I would do this with properties (the Pythonic replacement for endless gets and sets, see e.g. Python @property versus getters and setters), and leave only the input to a class method. Here is a minimal example:

class Relative: def __init__(self, first_name=None): self.first_name = first_name @staticmethod def _valid_name(name): return name is None or name.isalpha() # this will choke if name isn't None or a string - maybe add more rules? @property def first_name(self): return self._first_name @first_name.setter def first_name(self, new_name): if not self._valid_name(new_name): raise ValueError('Invalid first name: {!r}'.format(new_name)) self._first_name = new_name @classmethod def from_input(cls): relative = cls() while True: # you could alternatively use cls._valid_name directly here try: relative.first_name = input('Enter first name: ') except ValueError: print('Please try again.') else: break return relative

使用中:

>>> uncle_bob = Relative.from_input() Enter first name: 123 Please try again. Enter first name: * Please try again. Enter first name: Robert >>> uncle_bob.first_name 'Robert' >>> uncle_bob.first_name = '123' Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> uncle_bob.first_name = '123' File "<pyshell#11>", line 17, in first_name raise ValueError('Invalid first name: {!r}'.format(new_name)) ValueError: Invalid first name: '123'

注意: p>

Note that:

  • 将名称验证抽象为 Relative._valid_name ,可以轻松验证第一个和最后一个
  • 使用一个 @property 表示用户不能在任何时候设置不正确的名称,而不强制他们调用特定的方法来获取/设置值。
  • 我使用了一个<按照惯例内部变量的单下划线名称,而不是 name-mangled 双下划线 - 样式指南。 li>
  • Abstracting out the name validation to Relative._valid_name makes it easy to validate first and last names with the same rules (you could also add a middle name, and easily make that the same too).
  • Using a @property means that the user can't set an incorrect name at any point, without forcing them to call a specific method to get/set values.
  • I have used a private-by-convention single-underscore name for the internal variable, rather than a name-mangled double-underscore one - see e.g. the style guide.
  • 更多推荐

    类方法来创建新实例

    本文发布于:2023-11-09 20:30:36,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1573360.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:方法来   实例

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!