0

I'm trying to use a class variable on another class in on another script, but I'm not sure how that's possible. I've seen how to use methods or functions, but not variables.

For example something like this

#old.py

class Sassy:

    bbq = "nice"

    lol = "funny"

    def DoesNothing(self):

        #this is the method's body and nothing really goes here

How can I use bbq and lol on a new script?

Is this the right way?

#new.py

from old import *

class HeySexy:

    new = Sassy()

    def ShowMeThatString(self):

        print(self.new.bbq)        
3
  • I hope this is just a quick example of a class and not something you're trying to implement... Commented Feb 25, 2014 at 1:09
  • 1
    Relax, just an example lol Commented Feb 25, 2014 at 1:09
  • changed the question a bit. Sorry! lol Commented Feb 25, 2014 at 1:10

2 Answers 2

3

That's almost right.

Never do this:

from old import *

Instead do this:

from old import Sassy

new = Sassy()
print(new.bbq)
Sign up to request clarification or add additional context in comments.

1 Comment

@satoru is right that since bbq is a class variable, you can access it without creating a Sassy instance.
1

Yes, and since they are class variables, you can also do Sassy.bbq.

PS: As tsroten told you, import * is considered bad practice, because it'll make it difficult to find out where an object came from once your module become larger. You can read PEP8 if you want to learn more about Python coding style.

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.