简体   繁体   English

使用对象作为输入在python中定义方法

[英]Define method in python with an object as input

I just started with coding in python, at the moment I am trying to define a function that needs an object as input. 我刚开始使用python进行编码,此刻我正试图定义一个需要对象作为输入的函数。 Before this I just developed in Java. 在此之前,我只是用Java开发的。

def welcome_message(c):
    msg.send("Hi %s", c.first_name)

So this function works, I was wondering if I still should insert a constraint that c has to be on object of the type Customer? 因此,此功能有效,我想知道是否仍应插入必须位于类型Customer的对象上的约束? It just doesn't really feel safe for a java experienced developer... 对于Java经验丰富的开发人员来说,这确实并不安全...

The python way of thinking is that the programmer or those that use your software will be intelligent enough to use it properly so long as you've written and documented your software clearly. python的思维方式是,只要您已经清楚地编写和记录了软件,程序员或使用您的软件的人员就会足够聪明地正确使用它。 More that likely when passing in the object, c.first_name will barf if it's not the right type. 传递对象时, c.first_name的类型不正确的c.first_name One way to protect things is the following: 保护事物的一种方法如下:

def welcome_message(c):
    if isinstance(c, Customer):
        msg.send("Hi %s", c.first_name)
    else:
        raise TypeError("Class must be of type `Customer`")

However, I would recommend not doing this, unless it's absolutely necessary. 但是,除非绝对必要,否则我建议不要这样做。

If an object without a first_name attribute is passed, this will fail. 如果传递的对象没有first_name属性,则将失败。 So put that function body in a try ... except and decide what you want to do when it fails. 因此,请try ... except该函数体try ... except并确定失败时要执行的操作。

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

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