Livius
Livius

Reputation: 956

Python virtual method without crapping names

sample code what i am talking about

class A:
  def __init__(self):
    self.x = 5
  def virtual__getX(self):
    return self.x
  def getY(self):
    return self.virtual__getX()+2

class B(A):
  def __init__(self):
    A.__init__(self)
  def virtual__getX(self):
    return 20

a=A()
b=B()

print(a.getY())
print(b.getY())

is there a way in python 3 to have real virtual method without this really bad name "virtual__getX" i need clear names "__getX"

Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

7
22

if i remove virtual from name the result is

Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

7
7

is there better way to write real virtual methods like in "normal language" like delphi

Upvotes: 0

Views: 73

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43276

You can't have a virtual function named __something. Attributes starting with a double underscore are considered private, and python internally applies name-mangling to them.

You can, however, rename virtual__getX to getX and it'll work as you expect.

Upvotes: 1

Related Questions