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.
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). If you want to add functions to MSMeshface
(as you suggest in the comments), define a base class containing those functions such as:
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
. You can't influence the moment of creation of the object in the class's __init__
method, you can only initialize it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.