我遇到了一些严重的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:
更多推荐
类方法来创建新实例
发布评论