简体   繁体   English

python中的类定义错误

[英]class definition error in python

What is wrong with defining a class constructor like this: 定义这样的类构造函数有什么问题:

I am trying to construct two different objects based on whether input d stays None or gets value assigned. 我试图根据输入d保持None还是获取值分配来构造两个不同的对象。

class MSMeshFace(object):

    def __init__(self, a= None, b= None, c= None, d= None):
            self.a = a
            self.b = b
            self.c = c
            self.d = d
            if self.d == None:
                    triangleFace = MSMeshFace(self.a, self.b, self.c)
                    self.count = 3
                    return triangleFace
            else:
                    quadFace = MSMeshFace(self.a, self.b, self.c, self.d)
                    self.count = 4
                    return quadFace

The constructor (well, the initializer, really) is not supposed to return anything, it's supposed to initialize a newly created instance. 构造函数(实际上是初始化器)不应返回任何东西,而应初始化一个新创建的实例。 What you want is: 您想要的是:

class MSMeshFace(object):
    def __init__(self, a=None, b=None, c=None, d=None):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.count = 3 if self.d is None else 4

If you are trying to return an object of different types based on arguments, make a new function like: 如果您尝试基于参数返回不同类型的对象,请创建一个新函数,如:

def make_face(*args):
    if len(args) == 3:  # triangle face
        return TriMeshFace(*args)
    else:  # quad face
        return QuadMeshFace(*args)

You can't (normally) change type in a constructor (you may be able to in __new__ , though, but you don't need that for this). 您不能(通常)在构造函数中更改类型(尽管您可以在__new__中进行__new__ ,但是您不需要这样做)。 If you want to add functions to MSMeshface (as you suggest in the comments), define a base class containing those functions such as: 如果要向MSMeshface添加功能(如注释中所建议),请定义包含这些功能的基类,例如:

class MeshBase:
    def addData(self, data): pass
    def ToDSMeshFace(self): pass

class TriMeshFace(MeshBase): pass

class QuadMeshFace(MeshBase): pass

Your intention seems to be as follows: 您的意图似乎如下:

class MSMeshFace(object):
    def __init__(self, a= None, b= None, c= None, d= None):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.count = 3 if self.d is None else 4

The constructed object will be returned automatically. 构造的对象将自动返回。 The object already exists, and is pointed by self . 该对象已经存在,并由self指向。 You can't influence the moment of creation of the object in the class's __init__ method, you can only initialize it. 您不能在类的__init__方法中影响创建对象的时间,只能对其进行初始化

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

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