Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Design] reconstruction magic methods #281

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

khchen
Copy link

@khchen khchen commented Jul 21, 2022

  • add array of magic methods to class struct.
  • current magic methods: _init, _getter, _setter, _str, _repr, _call.
  • optimize method calling for magic methods.
  • add _call so that object can be callable.
  • add Object.getattr and Object.setattr so that attribs can be accessed via dynamic name.
  • getter/setter can be called in script, no only in native code.

* current magic methods: _init, _getter, _setter, _str, _repr, _call.
* optimize method calling for magic methods.
* add _call so that object can be callable.
* add Object.getattr and Object.setattr so that attribs can be accessed via
  dynamic name.
* getter/setter can be called in script, no only in native code.
@khchen
Copy link
Author

khchen commented Jul 21, 2022

Example (this example needs "[Bugfix] native class can be inherited in script" to run):

from types import Vector

class Vector2 is Vector
  def _init(x, y, z, a)
    super(x, y, z)
    self.a = a
  end

  def _setter(name, value)
    if name in ['x', 'y', 'z'] then
      super(name, value)
    else
      # last "true" means skip the default setter to avoid infinite loop
      self.setattr(name, value, true) 
    end
  end

  def _getter(name)
    if name in ['x', 'y', 'z'] then
      return super(name)
    else
      # last "true" means skip the default getter to avoid infinite loop
      return self.getattr(name, true)
    end
  end

  def _repr
    return super()[0..-2] + ", ${self.a}]"
  end

  def *=(n)
    self.x *= n; self.y *= n; self.z *= n; self.a *= n;
    return self
  end

  def _call
    print(self)
  end
end

v = Vector2(1, 2, 3, 4)
print(v)
v *= 2
v() # object is callable

Output:

[1, 2, 3, 4]
[2, 4, 6, 8]

@rdbyk
Copy link

rdbyk commented Jan 25, 2024

Please have a look at my comment/question here

7a736f1#r137787262

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants