-2

As title. the class set a attribute value inside inner class. then, access that inner attribute class from outer function. In below, attribute sets with inner function set_error. then, use outer function last_error to access the error.

class Device:
  error_info = ''

  def __init__(self):
    self.identify = self.Identify(self.error_info)

  def last_error(self):
    return self.error_info

  class Identify:
    def __init__(self, error):
      self.error_info = error

    def set_error(self, error):
      self.error_info = error

device = Device()

device.identify.set_error('test')

print(device.last_error())
David
  • 11
  • 4
  • 1
    what's ur desired output? test? – nonamer92 Dec 01 '19 at 22:37
  • @ranifisch yes, output should dependent what `set_error` function set. – David Dec 01 '19 at 22:38
  • 3
    As already suggested in the comments to your previous question, there is no advantage in defining `Identify` inside `Device`. – Thierry Lathuille Dec 01 '19 at 22:43
  • @ThierryLathuille I guess not. I think it do what i want. To access attribute and function like javascript. – David Dec 01 '19 at 22:55
  • 1
    @David how does nesting this class help you access the attributes like JavaScript? You can do that without the class nesting. There is no advantage, and it is very irregular. – juanpa.arrivillaga Dec 01 '19 at 23:04
  • @juanpa.arrivillaga Is there other ways or python style that can access object like javascript? **device.identify.manufacturer**? is there ways to make 2 object share attribute and function. then use the class like javascript style? – David Dec 01 '19 at 23:09
  • @juanpa.arrivillaga Last day, i try to use PyQt5 module. I feels javascript style when use the module. Set attribute that needed first. Then, call a function. – David Dec 01 '19 at 23:10
  • Does this answer your question? [How to access outer attribute class within inner class?](https://stackoverflow.com/questions/59129879/how-to-access-outer-attribute-class-within-inner-class) – AMC Dec 02 '19 at 00:39
  • @David of course you can access an attribute like `device.identity.manufacturer`, you can do that in partially any OOP language, JavaScript isn't unique in that at all. You can do that in your own code, just unnest your `Identify` class and it will work exactly the same. Just use `Identify` instead of `self.Identify` in the `Device.__init__`. nesting your classes here does nothing useful – juanpa.arrivillaga Dec 02 '19 at 01:14

1 Answers1

0

change last_error to:

  def last_error(self):
    return self.identify.error_info

You want to get identify's error. you have initialized identify in the constructor so you can use it now.

nonamer92
  • 1,887
  • 1
  • 13
  • 24
  • Wow, So stupid am i. I don't recognize it. Now i can reconstruct like javascript style. – David Dec 01 '19 at 22:56