Skip to content

Instantly share code, notes, and snippets.

@ajtritt
Created March 13, 2018 21:49
Show Gist options
  • Save ajtritt/3e4f3cc66b5de5c34cee56efbec88d30 to your computer and use it in GitHub Desktop.
Save ajtritt/3e4f3cc66b5de5c34cee56efbec88d30 to your computer and use it in GitHub Desktop.
demonstrate override property
class MyClass(object):
def __init__(self, p):
self.__x = p
@property
def x(self):
return self.__x
@x.setter
def x(self, p):
self.__x = p
class MySubClass(MyClass):
def __init__(self, p):
self.__x = p
@property
def x(self):
return self.__x
foo = MyClass(10)
print('Should be 10:', foo.x)
foo.x = 20
print('Should be 20:', foo.x)
bar = MySubClass(30)
print('Should be 30:', bar.x)
print("Setting x, should raise AttributeError")
bar.x = 20
#print('Should be 20:', bar.x)
@mamelara
Copy link

mamelara commented Mar 13, 2018

class MyClass(object):

    def __init__(self, f):
        self.__f = f

    @property
    def bar(self):
        return str(self.__f) + " from bar"

    @property
    def foo(self):
        return self.bar

def find_f():
    return MyClass(10)

class Package(object):

    def __init__(self):
        self.x = 0

    @property
    def f_interface(self):
        return find_f()


# actual interface
print(ClassCreator().f_interface.foo)
# >> 10 from bar

# want
# >> 10 baz

@mamelara
Copy link

Tried my best to mimic what is happening. I basically don't want to change the interface because that is being used a lot.

@mamelara
Copy link

And let's just say that f_inteface creates a lot of objects through some important methods. So subclass MyClass and replacing it in f_interface is not as easy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment