-1

I want to access one class attribute s and split it into 2 strings in another class. Any tips?

class lyssna:
    def du():
        s = '5-22'

class Fixish():

    strt, stpp = lyssna.s.split('-')
ata
  • 3,398
  • 5
  • 20
  • 31
  • 1
    `lyssna` indeed doesn't have an attribute `s`, what makes you think it does? It has a method `du()` that defines a local variable called `s`, that's all. – Daniel Roseman Apr 09 '18 at 17:33
  • 2
    Possible duplicate of [Access a function variable outside the function without using \`global\`](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global) – Xantium Apr 09 '18 at 17:38
  • I see several potential discrepancies in your understanding of classes in general, and Python classes in particular. I recommend that you work through a tutorial; there are many available on line. I can't accurately suggest a way to "fix" your code, since it's not at a ll clear what you're trying to achieve. – Prune Apr 09 '18 at 17:39

1 Answers1

1

lyssna is a class whose only (manually declared) attribute is du, a method. It's expected that s is not available from lyssna as s is a variable whose scope is restricted to du.

I don't know exactly why you want to define classes to do that job, because you can simply define a function as follows:

def split_hyphen(text):
    return text.split('-', maxsplit=1)

If the text of interest is an attribute of another class, you can access it using:

class A:
   text_of_intereset = '1-2'

split_hyphen(A.text_of_interest)

If it is an attribute of an instance of another class:

class A:
    def __init__(self, text_as_parameter):
        self.text_of_interest = text_as_parameter

# Create an instance of A
a = A('1-2')

split_hyphen(a.text_of_interest)
Guybrush
  • 2,680
  • 1
  • 10
  • 17