Method reference in attribute before method is defined causing error
I don't understand why this works;
class parentClass(object):
pass
class childClass(parentClass):
def my_meth(var):
print(var)
a = {'meth': my_meth}
x = childClass.a['meth']("Helloworld")
Whilst this fails;
class parentClass(object):
pass
class childClass(parentClass):
a = {'meth': my_meth}
def my_meth(var):
print(var)
x = childClass.a['meth']("Helloworld")
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
python python-3.x class attributes
add a comment |
I don't understand why this works;
class parentClass(object):
pass
class childClass(parentClass):
def my_meth(var):
print(var)
a = {'meth': my_meth}
x = childClass.a['meth']("Helloworld")
Whilst this fails;
class parentClass(object):
pass
class childClass(parentClass):
a = {'meth': my_meth}
def my_meth(var):
print(var)
x = childClass.a['meth']("Helloworld")
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
python python-3.x class attributes
I think the problem here is that you are calling the function before defining it though you can define functions in any order.
– BernardL
Nov 26 '18 at 5:35
1
"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.
– juanpa.arrivillaga
Nov 26 '18 at 6:20
add a comment |
I don't understand why this works;
class parentClass(object):
pass
class childClass(parentClass):
def my_meth(var):
print(var)
a = {'meth': my_meth}
x = childClass.a['meth']("Helloworld")
Whilst this fails;
class parentClass(object):
pass
class childClass(parentClass):
a = {'meth': my_meth}
def my_meth(var):
print(var)
x = childClass.a['meth']("Helloworld")
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
python python-3.x class attributes
I don't understand why this works;
class parentClass(object):
pass
class childClass(parentClass):
def my_meth(var):
print(var)
a = {'meth': my_meth}
x = childClass.a['meth']("Helloworld")
Whilst this fails;
class parentClass(object):
pass
class childClass(parentClass):
a = {'meth': my_meth}
def my_meth(var):
print(var)
x = childClass.a['meth']("Helloworld")
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
python python-3.x class attributes
python python-3.x class attributes
asked Nov 26 '18 at 5:26
myolmyol
1,83974074
1,83974074
I think the problem here is that you are calling the function before defining it though you can define functions in any order.
– BernardL
Nov 26 '18 at 5:35
1
"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.
– juanpa.arrivillaga
Nov 26 '18 at 6:20
add a comment |
I think the problem here is that you are calling the function before defining it though you can define functions in any order.
– BernardL
Nov 26 '18 at 5:35
1
"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.
– juanpa.arrivillaga
Nov 26 '18 at 6:20
I think the problem here is that you are calling the function before defining it though you can define functions in any order.
– BernardL
Nov 26 '18 at 5:35
I think the problem here is that you are calling the function before defining it though you can define functions in any order.
– BernardL
Nov 26 '18 at 5:35
1
1
"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.
– juanpa.arrivillaga
Nov 26 '18 at 6:20
"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.
– juanpa.arrivillaga
Nov 26 '18 at 6:20
add a comment |
1 Answer
1
active
oldest
votes
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
Your first example is fine. The order is not considered strange in Python.
That said, you do have potential alternatives. You could, for example, create a @classmethod
to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.
class childClass(parentClass):
@classmethod
def _initialize(cls)
cls.a = {'meth': cls.my_meth}
def my_meth(var):
print(var)
childClass._initialize()
You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.
Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.
Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo()
inside of a method bar
, the .
operator is doing an attribute lookup of the foo
attribute on the self
object. It's a similar idea when using cls.foo()
in a classmethod.
It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError
, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53475170%2fmethod-reference-in-attribute-before-method-is-defined-causing-error%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
Your first example is fine. The order is not considered strange in Python.
That said, you do have potential alternatives. You could, for example, create a @classmethod
to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.
class childClass(parentClass):
@classmethod
def _initialize(cls)
cls.a = {'meth': cls.my_meth}
def my_meth(var):
print(var)
childClass._initialize()
You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.
Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.
Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo()
inside of a method bar
, the .
operator is doing an attribute lookup of the foo
attribute on the self
object. It's a similar idea when using cls.foo()
in a classmethod.
It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError
, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.
add a comment |
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
Your first example is fine. The order is not considered strange in Python.
That said, you do have potential alternatives. You could, for example, create a @classmethod
to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.
class childClass(parentClass):
@classmethod
def _initialize(cls)
cls.a = {'meth': cls.my_meth}
def my_meth(var):
print(var)
childClass._initialize()
You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.
Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.
Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo()
inside of a method bar
, the .
operator is doing an attribute lookup of the foo
attribute on the self
object. It's a similar idea when using cls.foo()
in a classmethod.
It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError
, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.
add a comment |
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
Your first example is fine. The order is not considered strange in Python.
That said, you do have potential alternatives. You could, for example, create a @classmethod
to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.
class childClass(parentClass):
@classmethod
def _initialize(cls)
cls.a = {'meth': cls.my_meth}
def my_meth(var):
print(var)
childClass._initialize()
You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.
Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.
Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo()
inside of a method bar
, the .
operator is doing an attribute lookup of the foo
attribute on the self
object. It's a similar idea when using cls.foo()
in a classmethod.
It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError
, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.
It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?
Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.
Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?
Your first example is fine. The order is not considered strange in Python.
That said, you do have potential alternatives. You could, for example, create a @classmethod
to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.
class childClass(parentClass):
@classmethod
def _initialize(cls)
cls.a = {'meth': cls.my_meth}
def my_meth(var):
print(var)
childClass._initialize()
You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.
Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?
Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.
Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo()
inside of a method bar
, the .
operator is doing an attribute lookup of the foo
attribute on the self
object. It's a similar idea when using cls.foo()
in a classmethod.
It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError
, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.
edited Nov 26 '18 at 6:32
answered Nov 26 '18 at 5:41
gilchgilch
3,8901716
3,8901716
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53475170%2fmethod-reference-in-attribute-before-method-is-defined-causing-error%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I think the problem here is that you are calling the function before defining it though you can define functions in any order.
– BernardL
Nov 26 '18 at 5:35
1
"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.
– juanpa.arrivillaga
Nov 26 '18 at 6:20