简体   繁体   English

Python 3-在OOP中搜索

[英]Python 3 - Searching in OOP

I'm fairly new to programming and have been self teaching myself python in my free time. 我对编程还很陌生,并且一直在空闲时间自学python。 I'm really trying to under stand OOP and have hit a wall. 我真的是想站在OOP之下并且碰壁。 This is a smaller example of a larger program I am writing. 这是我正在编写的较大程序的较小示例。

class Emp():
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def PrintEmp(self):
        return (self.first, self.last, self.age)

employee = {}

employee[0] = {'Info': {'First': 'Jacob', 'Last': 'Jones', 'Age': 31}}
employee[1] = {'Info': {'First': 'Joe', 'Last': 'Smith', 'Age': 45}}
employee[2] = {'Info': {'First': 'Jim', 'Last': 'Bob', 'Age': 38}}
employee[3] = {'Info': {'First': 'Jack', 'Last': 'Black', 'Age': 21}}
employee[4] = {'Info': {'First': 'Joey', 'Last': 'John', 'Age': 39}}
employee[5] = {'Info': {'First': 'Job', 'Last': 'God', 'Age': 99}}

for key in employee:
    employee[key]['Info']['First'] = Emp(employee[key]['Info']['First'],
                                     employee[key]['Info']['Last'],
                                     employee[key]['Info']['Age'])

choice = input('Employee')

for key in employee:
    if choice == employee[key]['Info']['First']:
        print(choice.PrintEmp)
        #choice.first, choice.last, choice.age ect...
    else:
        print("This isn't working")

I am basically trying to search through a list of known employees and then print anything from the actual object or just search directly through the objects for specific attributes. 我基本上是在尝试搜索已知员工的列表,然后打印实际对象中的所有内容,或者直接在对象中搜索特定属性。

choice probably wont match anything because you're comparing the user input string to an Emp instance. choice可能不会匹配任何内容,因为您正在将用户输入字符串与Emp实例进行比较。

If you removed: 如果删除:

for key in employee:
    employee[key]['Info']['First'] = Emp(employee[key]['Info']['First'],
                                     employee[key]['Info']['Last'],
                                     employee[key]['Info']['Age'])

You should be able to at least iterate through and match employees based on First name. 您应该至少能够根据名字迭代并匹配员工。


As for OOP, I would recommend starting at SOLID, which are 5 design principles and provide a great guideline for OOP development. 对于OOP,我建议从SOLID开始,这是5条设计原则,并为OOP开发提供了很好的指导。

https://en.wikipedia.org/wiki/SOLID_(object-oriented_design) https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

I think their strongest suite is that they give us some concepts to evaluate code by, and give us a place to start talking, and provide us with shared terminology. 我认为他们最强的套件是给我们一些概念来评估代码,并为我们提供一个开始讨论的地方,并为我们提供共享的术语。


2 amazingly useful concepts of programming and OOP are: encapsulation and delegation. 编程和OOP的两个非常有用的概念是:封装和委派。

I could imagine a collection of employees that exposes a search() method. 我可以想象有一组员工公开了search()方法。 This would insulate your main code from having to change as your improve/change your search implementation and it isolates search logic to only parts of the program that require to know the specifics of it. 这可以使您的主要代码免于在改进/更改搜索实现时必须进行更改,并且可以将搜索逻辑仅隔离于需要了解特定信息的程序部分。

Welcome to programming! 欢迎编程! I started teaching myself a little under a year ago, so I can relate to any frustrations that may arise when learning a new concept. 我不到一年前就开始自学,所以我可以将学习新概念时可能遇到的挫败感联系起来。

I'll start with what you're trying to accomplish first - invoking your PrintEmp method of an Emp instance. 我将从您首先要完成的事情开始-调用Emp实例的PrintEmp方法。 The reason your current code isn't working as you would like is because you're iterating through every employee (When I think you really just want to find a match), and then your condition will never evaluate as intended because choice is a str object and your keys in employee are integers. 您当前的代码无法按预期运行的原因是因为您正在遍历每个employee (当我认为您真的只想找到一个匹配项时),然后您的条件将永远无法按预期进行评估,因为choice是一个str object和您在employee中的键是整数。 In the following example I start by grabbing the dictionary containing the needed values to create an instance of Emp with info = value['Info'] . 在下面的示例中,我首先获取包含所需值的字典,以使用info = value['Info']创建Emp的实例。 Of the dictionary now stored in the variable info I can grab the values I need with info.values() and then I unpack those values as arguments for each Emp instance that is created. 在现在存储在变量info的字典中,我可以使用info.values()获取所需的值,然后将这些值解压缩为所创建的每个Emp实例的参数。 Now that each dictionary has been converted to an Emp object we can call PrintEmp as we'd like. 现在,每个字典都已转换为Emp对象,我们可以根据需要调用PrintEmp

Note: I took the liberty of changing your naming of the dictionary employee to employees as it's a bit more accurate. 注意:我可以自由地将字典employee命名更改为employees因为这样更准确。

# Here we instantiate each `employee`
for key, value in employees.items():
    info = value['Info']  # e.g. here I now have {'First': 'Jacob', 'Last': 'Jones', 'Age': 31}

    # Now I am going to create an `Emp` instance for each dictionary in `employees`
    employees[key] = Emp(*info.values())

choice = int(input('Enter an employee index: '))

if choice in employees:
    print(employees[choice].PrintEmp())
else:
    "That still isn't working..."

Running the program now: 现在运行程序:

>>> Enter an employee index: 2
returning: ('Jim', 'Bob', 38)

Say you wanted to format the output of your PrintEmp method - you can use the str.format method like so: 假设您想格式化PrintEmp方法的输出-您可以像这样使用str.format方法:

def PrintEmp(self):
    # Note the type conversion for self.age
    return "Hi my name is {} {}, and I'm {}!".format(self.first, self.last, str(self.age))

Running the program now: 现在运行程序:

>>> Enter an employee index: 2
returning: Hi my name is Jim Bob, and I'm 38!

If there's anything you would like clarification on, don't hesitate to ask! 如果您有任何要澄清的信息,请随时询问!

As already noted by dm03514 your if-condition did not work, because you were comparing a string with a class instance. dm03514所述,您的if-condition不起作用,因为您正在将字符串与类实例进行比较。

Next issue, PrintEmp() is a function of Emp and not choice, therefore print(choice.PrintEmp) does not work. 下一期,PrintEmp()是Emp的函数,而不是选择函数,因此print(choice.PrintEmp)不起作用。

You may want to try this: 您可能要尝试以下操作:

class Emp():
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def PrintEmp(self):
        return (self.first, self.last, self.age)

employee = {}

employee[0] = {'Info': {'First': 'Jacob', 'Last': 'Jones', 'Age': 31}}
employee[1] = {'Info': {'First': 'Joe', 'Last': 'Smith', 'Age': 45}}
employee[2] = {'Info': {'First': 'Jim', 'Last': 'Bob', 'Age': 38}}
employee[3] = {'Info': {'First': 'Jack', 'Last': 'Black', 'Age': 21}}
employee[4] = {'Info': {'First': 'Joey', 'Last': 'John', 'Age': 39}}
employee[5] = {'Info': {'First': 'Job', 'Last': 'God', 'Age': 99}}


employees = []
for key in employee:
    employees.append(
        Emp(
            employee[key]['Info']['First'],
            employee[key]['Info']['Last'],
            employee[key]['Info']['Age']
        )
    )

choice = input('Employee first name:\n')

for employee in employees:
    if choice == employee.first:
        print (employee.PrintEmp())
    else:
        print("This isn't working")

Returns for 'Jim': 返回“吉姆”:

This isn't working
This isn't working
('Jim', 'Bob', 38)
This isn't working
This isn't working
This isn't working

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM