1
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?

4
  • 1
    1. No, this is not Visual Basic. 2. Why not use the builtin complex type? Commented Jan 5, 2011 at 18:11
  • Propably not possible (without vastly modifying the language, which you won't achive anyway) - but how about C = ReallyReallyLongClassName and using C.realpart instead? And consider if it should be a class-level constant anyway... (Edit @AdniDog: You're missing the point. VB isn't the only language that does scoping different from Python, and the class name is just an - albeit not very well-chosen - example) Commented Jan 5, 2011 at 18:11
  • In any way, there's no use for shortening statements in Python. C = WayTooLongClassName is a solution, but I don't remember ever having used something like this in Python. I chose VB as an example by intention, because statements there can get very long. Commented Jan 5, 2011 at 18:17
  • Python has built-in support for complex numbers; you can just use x = 0+0j. Commented Jan 5, 2011 at 18:38

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

hi, what's the use of object in Complex(object)?
It's what it inherits from. All new-style classes ultimately inherit from object. For example to make a SuperComplex class inheriting from Complex, you would write it as class SuperComplex(Complex):
0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.