简体   繁体   English

使用 Python 创建 class 的实例

[英]Creating instances of a class using Python

What does the () actually do when creating an instance of a class in Python. I can create classes by在 Python 中创建 class 的实例时, ()实际上做了什么。我可以创建类

class class_A:
    pass

but when I try to call it但是当我尝试调用它时

instance_of_A = class_A 
type(instance_of_A)

I get <class 'type'> returned我得到<class 'type'>返回

but when I use the parenthesis:但是当我使用括号时:

instance_of_A =class_A()
type(instance_of_A)

I get <class '__main__.classA'>我得到<class '__main__.classA'>

I understand that it is essential, but I don't understand why.我知道这是必不可少的,但我不明白为什么。

In your 1st statement, you are just assigning class A to the variable "instance_of_A".在您的第一个语句中,您只是将 class A 分配给变量“instance_of_A”。 In your 2nd statement (where you used parenthesis), you are actually creating an instance of class A.在您的第二条语句(您使用括号的地方)中,您实际上是在创建 class A 的实例。

I think you need a little bit of clarity about OOP in python. Let me explain a bit how OOP works in python:我认为您需要稍微了解一下 python 中的 OOP。让我解释一下 OOP 在 python 中的工作原理:

Class is like a blueprint, and the instance is like a product for that blueprint (class). Class 就像一个蓝图,实例就像是那个蓝图(类)的产品 You can only use the object and not a class (not speaking about static methods)您只能使用 object 而不能使用 class(不是说 static 方法)

class Phone:
__balance = 0
__numberOfCalls = 0
def __init__(self):
    self.__balance = 1
    print("Yeah!, New Phone")

def makeCall(self):
    if self.__balance < 1:
        print('Please recharge and try again')
        return
    self.__numberOfCalls += 1
    self.__balance -= 1
    print("Making call %d" %(self.__numberOfCalls))

In the above example, we have a simple example class Phone.在上面的例子中,我们有一个简单的例子 class 电话。

samsung = Phone()    # Yeah!, New Phone
samsung.makeCall()   # Making call 1
samsung.makeCall()   # Please recharge and try again

Here you can clearly understand that variables inside class Phone ( __balance, __numberOfCalls ) belong to the created instance (Samsung).这里可以清楚的了解到class Phone里面的变量(__balance, __numberOfCalls)属于创建的实例(Samsung)。 In our example, Samsung can't make the second call, because it has zero balance (Note: Samsung has zero balance not the Phone).在我们的示例中,三星无法拨打第二个电话,因为它的余额为零(注意:三星的余额为零,而不是手机)。 If you create a new phone (may be onePlus), you can make another call.如果您创建一部新手机(可能是 onePlus),您可以拨打另一个电话。

What parenthesis do with class? class 的括号是什么?

When you call a class it returns a new instance of the class. But when you just assign it to a variable without calling it, no instance is created.当您调用 class 时,它会返回 class 的一个新实例。但是当您只是将它分配给一个变量而不调用它时,不会创建任何实例。

apple = Phone
apple.makeCall()    # TypeError: makeCall() missing 1 required positional argument: 'self'

This threw an error(which is expected), because we have not called Phone, so it wont return the instance of the Phone, instead we are assigning Phone(class) to apple.这引发了一个错误(这是预期的),因为我们没有调用 Phone,所以它不会返回 Phone 的实例,而是我们将 Phone(class) 分配给苹果。
If you are coming from other languages such as javascript, you may be expected "method not found exception".如果您来自其他语言,例如 javascript,您可能会收到“找不到方法的异常”。 But here what we got is Type Error, missing positional argument 'self' .但在这里我们得到的是类型错误,缺少位置参数 'self'

Python takes its own instance as its 1st argument self (the name self is just a convention, not a keyword), that's why we are writing the self in all method declarations. Python 将它自己的实例作为它的第一个参数self (名称 self 只是一个约定,而不是关键字),这就是我们在所有方法声明中写 self 的原因。 We don't have to pass the instance as parameters, python handles it when you call the method from the instance.我们不必将实例作为参数传递,当您从实例调用方法时,python 会处理它。

Here comes a new question...新问题来了……

apple = Phone
apple.makeCall(samsung)

Will the above code work?上面的代码会工作吗?

yes, as I said, you don't have to pass an instance as a parameter when you call the method via the instance itself.是的,正如我所说,当您通过实例本身调用方法时,您不必将实例作为参数传递。 Here apple is just a class (not an instance), And as per the previous error, we are passing the required positional argument Samsung(which is an instance of Phone).这里的 apple 只是一个 class(不是一个实例),并且根据之前的错误,我们传递了所需的位置参数 Samsung(它是 Phone 的一个实例)。 This is similar to the below code.这类似于下面的代码。

samsung.makeCall()

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

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