class Complex:
realpart,imagpart=0,0
def __init__(self):
self.r = Complex.realpart
self.i = Complex.imagpart
x = Complex()
the above code works, x.r,x.i = (0,0)开发者_开发问答, but when the class name is big, Class_name.Data_member way of accessing class data looks very redundant, is there any way to improve the class scoping, so I don't have to use Complex.imagpart? just use self.r = realpart?
This is what you want to do:
class Complex(object):
def __init__(self, realpart=0, imagpart=0):
self.realpart = realpart
self.imagpart = imagpart
Accessing the member variables is the "self.realpart" call. What you were using is class attributes which are accessed like this:
Complex.some_attribute
No. The data members you specified above are attributes of the class, and therefore require the class name to be specified. You could use self.r = self.__class__.realpart
if you prefer. It seems as though you're just using these values as initializers though, so having realpart
and imagpart
at all is redundant.
(Also, note that Python has native support for complex numbers. Just write them such as 5+3j.)
精彩评论