I have the following code:
def __static_func(name):
print 'Name = ' + name
class A:
def __init__(self, name):
self.name = name
def fun(self):
__static_func(self.name)
a = A('foo')
a.fun()
When launched on Python 2.7, it produces
NameError: global name '_A__static_func' is not defined
So the question is how do I call global function from within class method?
I was recently reading a book "Learning Python by O'Reilly" (Page 944, Chapter 31) and it was mentioned that when you use double underscores __ as the starting characters of a method or a variable in the Class, it automatically appends the _classname to that function where classname is the class name. This is done to localize a name to the class to which it belongs. This is called Name Mangling in the context of Pseudoprivate class attributes.
This way you can use the same name __variable in two different classes A and B as the variables/methods will become privately _A__variable and _B__variable respectively. So just name your global function something else with a single underscore for example to avoid this conflict.
Don't use double underscores.
def _static_func(name):
print 'Name = ' + name
class A:
def __init__(self, name):
self.name = name
def fun(self):
_static_func(self.name)
a = A('foo')
a.fun()
Should work
Related
I am trying to characterise my class with init but the website says I have to add the last two lines of code but I don't know what they do? Could someone explain?
Code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("My awesome name is " + self.name)
p1 = Person("bob", 69)
p1.myfunc()
It is pretty simple. Let's say you create a string.
a = "Hello"
This basically creates a new string object called a. Now you can use a variety of functions like .isdigit(), .isalnum() etc. These functions are basically the functions of the String class and when called, they perform the function in relation to the object they are associated with.
So Saying,
print(a.isalnum())
Would give True as the function is defined to check of the String object is alphanumeric.
In the same way,
p1 = Person("bob", 69)
p1.myfunc()
First-line creates a new Person object with name='bob' and age=69. The second line then calls the function myfunc() in association with the Person p1 and executes with the attributes of p1 as its own local variables.
The first chunk of code is defining a class. This says what the class should be called, what attributes it has, and defines its behaviour.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("My awesome name is " + self.name)
Once those lines are run, the class exists in your session, but no instances of it do.
This creates an instance of the class:
p1 = Person("bob", 69)
And this line is that instance calling its method myfunc():
p1.myfunc()
I've tried to make an OOP based program in python. I gave it an object to work with and tried to make it print the name, but its not working.
class human:
def __init__(self, name):
print("this is a human")
def name(self, name):
print("this is {}".format(bob.name))
bob = human("bob")
Anyone know what the problem could be?
Beyond the answers you already received (which solve your problem), I'd suggest not having a method that prints the name. Rather, you should have a __str___ dunder method that defines the object's behavior when an instance is printed.
class human:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
person = human("bob")
print(person)
'bob'
You can also define the object's behavior when the instance name is entered in the console, for instance just running the line
>>> person
You can do it with __repr__:
def __repr__(self):
return f'when entering the instance name in the console: {self.name}'
This will print:
when entering the instance name in the console: bob
This appears more pythonic to me than having a method that simply prints the name.
You're never storing the name on the instance, where would it get the name from? Your __init__ needs to do something along the lines of self.name = name
the name method and attribute are going to conflict, the latter will shadow (hide) the former, and it should look up whatever attribute its using on self
You never assigned the passed name to the object. Try:
class human:
def __init__(self, name):
print("this is a human")
self.name = name
def print_name(self):
print("this is {}".format(self.name))
bob = human("bob")
bob.print_name()
there are couple of things to update in the code:
bob is an instance which is not defined at human class
notice that init, name functions expect external param but you never use it in the function. (in self. = name)
in order to use it:
define a var in the class named 'name' and update you function to:
class human:
_name = ""
def __init__(self, name):
print("this is a human")
self._name = name
def name(self):
print("this is "+ self._name)
bob = human("bob")
bob.name()
bob = human("bob") only init function and you should call bob.name() in order to call the print-name function
I'm trying to understand scope in nested classes in Python. Here is my example code:
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
The creation of class does not complete and I get the error:
<type 'exceptions.NameError'>: name 'outer_var' is not defined
Trying inner_var = Outerclass.outer_var doesn't work.
I get:
<type 'exceptions.NameError'>: name 'OuterClass' is not defined
I am trying to access the static outer_var from InnerClass.
Is there a way to do this?
class Outer(object):
outer_var = 1
class Inner(object):
#property
def inner_var(self):
return Outer.outer_var
This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var. (If you change what object the name Outer is bound to, then this code will use that object the next time it is executed.)
If you instead want all Inner objects to have a reference to an Outer because outer_var is really an instance attribute:
class Outer(object):
def __init__(self):
self.outer_var = 1
def get_inner(self):
return self.Inner(self)
# "self.Inner" is because Inner is a class attribute of this class
# "Outer.Inner" would also work, or move Inner to global scope
# and then just use "Inner"
class Inner(object):
def __init__(self, outer):
self.outer = outer
#property
def inner_var(self):
return self.outer.outer_var
Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer to Inner, if you want.)
I think you can simply do:
class OuterClass:
outer_var = 1
class InnerClass:
pass
InnerClass.inner_var = outer_var
The problem you encountered is due to this:
A block is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class
definition.
(...)
A scope defines the visibility of a name within
a block.
(...)
The scope of names defined in a class block is
limited to the class block; it does not extend to the code blocks of
methods – this includes generator expressions since they are
implemented using a function scope. This means that the following will
fail:
class A:
a = 42
b = list(a + i for i in range(10))
http://docs.python.org/reference/executionmodel.html#naming-and-binding
The above means:
a function body is a code block and a method is a function, then names defined out of the function body present in a class definition do not extend to the function body.
Paraphrasing this for your case:
a class definition is a code block, then names defined out of the inner class definition present in an outer class definition do not extend to the inner class definition.
You might be better off if you just don't use nested classes. If you must nest, try this:
x = 1
class OuterClass:
outer_var = x
class InnerClass:
inner_var = x
Or declare both classes before nesting them:
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = OuterClass.outer_var
OuterClass.InnerClass = InnerClass
(After this you can del InnerClass if you need to.)
Easiest solution:
class OuterClass:
outer_var = 1
class InnerClass:
def __init__(self):
self.inner_var = OuterClass.outer_var
It requires you to be explicit, but doesn't take much effort.
In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.
class OuterClass:
def __init__(self):
self.outer_var = 1
self.inner_class = OuterClass.InnerClass(self)
print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)
class InnerClass:
def __init__(self, outer_class):
self.outer_class = outer_class
self.inner_var = 2
print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)
All explanations can be found in Python Documentation The Python Tutorial
For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:
There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.
quoted from The Python Tutorial 9.4
For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined
When a class definition is left normally (via the end), a class object is created.
quoted from The Python Tutorial 9.3.1
So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined
A more detailed but tedious explanation for your first error:
Although classes have access to enclosing functions’ scopes, though, they do not act
as enclosing scopes to code nested within the class: Python searches enclosing functions
for referenced names, but never any enclosing classes. That is, a class is a local scope
and has access to enclosing local scopes, but it does not serve as an enclosing local scope
to further nested code.
quoted from Learning.Python(5th).Mark.Lutz
class c_outer:
def __init__(self, name:str='default_name'):
self._name = name
self._instance_lst = list()
self._x = self.c_inner()
def get_name(self):
return(self._name)
def add_inner_instance(self,name:str='default'):
self._instance_lst.append(self.c_inner(name))
def get_instance_name(self,index:int):
return(self._instance_lst[index].get_name())
class c_inner:
def __init__(self, name:str='default_name'):
self._name = name
def get_name(self):
return(self._name)
outer = c_outer("name_outer")
outer.add_inner_instance("test1")
outer.add_inner_instance("test2")
outer.add_inner_instance("test3")
inner_1 = outer.c_inner("name_inner1")
inner_2 = outer.c_inner("name_inner2")
inner_3 = outer.c_inner("name_inner3")
print(outer.get_instance_name(index=0))
print(outer.get_instance_name(1))
print(outer._instance_lst[2]._name
print(outer.get_name())
print(inner_1.get_name())
print(inner_2.get_name())
test1
test2
test3
name_outer
name_inner1
name_inner2
name_inner3
class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(myname):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(myname)
# Use the class to introduce Mark and Steve
mark = Person("Mark")
steve = Person("Steve")
print(mark.introduction())
print(steve.introduction())
its suppose to produce
"Hi, my name is Mark." or "Hi, my name is Steve."
but instead it produces
"Hi, my name is undefined."
It should be printing the object's representation in memory (something along the lines of Hi, my name is <__main__.Person object at 0x005CEA10>).
The reason is that the first argument of a method is expected to be the object that the method is called upon.
Just like you have def __init__(self, name): you should have def introduction(self, myname):.
Then you will encounter another problem, as introduction now expects an argument myname which you don't provide. However, it is not needed now since you have access to self.myname.
class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(self):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(self.myname)
# Use the class to introduce Mark and Steve
mark = Person("Mark")
steve = Person("Steve")
print(mark.introduction())
print(steve.introduction())
Will output
Hi, my name is Mark.
Hi, my name is Steve.
You need to declare introduction() -> introduction(self) as an instance method (by passing in self) to be able to access the instance variable self.myname.
class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(self):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(self.myname)
Sample output:
# Use the class to introduce Mark and Steve
mark = Person("Mark")
steve = Person("Steve")
print(mark.introduction())
print(steve.introduction())
>>> Hi, my name is Mark.
>>> Hi, my name
Please note however, that the first parameter in a function within a class is reserved for either a class, or object to pass itself to (unless a #staticmethod tag is applied to the method, then the first implicit parameter is not passed; which essentially behave as module methods).
Also keep in mind that self is not a reserved word, so you could name it anything (even though self is PEP convention). The below example executes the same output as the example above, and is semantically the same.
def introduction(myname):
"""Returns an introduction for this person."""
return "Hi, my name is {}.".format(myname.myname)
9.3.5. Class and Instance Variables
Your problem is that your giving your introduction method the parameter myname, but never supplying it with a valid argument.You can simply do:
mark = Person(" Mark")
steve = Person(" Steve")
print(mark.introduction(mark.myname))
print(steve.introduction(steve.myname))
your giving the introduction method, the variable from your class myname.
But the above is not even necessary. Since your initializing your name variable in the __init__ method of your class, it is like a global variable. So you can simply say:
class Person:
def __init__(self, name):
"""Make a new person with the given name."""
self.myname = name
def introduction(self):
"""Returns an introduction for this person."""
return "Hi, my name is{}".format(self.myname)
# Use the class to introduce Mark and Steve
mark = Person(" Mark")
steve = Person(" Steve")
print(mark.introduction())
print(steve.introduction())
I would like to create an object that holds and creates different objects within itself.
I have an outer class and inner classes, like this:
class Outer:
def __init__(self, name):
self.name = name
def sayHello(self):
print "Hello " + self.name
class Inner1:
def __init__(self, name):
self.name = name
class Inner2(Inner1):
pass
class Inner3(Inner1):
pass
new = outer("new")
And then new needs to make on object of inner2 or inner3...
I tried it with new.inner2()
but I don´t get the result I want.
Any tips?
Here is how you would do nested classes and nested instantiations. When you're embedding the classes, you're only embedding the types. You have to create the instances in self.__init__
(If you're trying to do global inner instances shared among all Outer instances please update your question.)
class Outer(object):
class Inner1(object):
pass
class Inner2(Inner1):
pass
class Inner3(Inner2):
pass
def __init__(self):
self.inner1 = Outer.Inner1()
self.inner2 = Outer.Inner2()
self.inner3 = Outer.Inner3()
outer = Outer()
print outer.inner1
print outer.inner2
print outer.inner3
Note that you don't have to actually use nested classes for this -- your classes can be defined outside of your class, and is sometimes preferred as simpler and more Pythonic:
class Inner1(object):
pass
class Inner2(Inner1):
pass
class Inner3(Inner2):
pass
class Outer(object):
def __init__(self):
self.inner1 = Inner1()
self.inner2 = Inner2()
self.inner3 = Inner3()
outer = Outer()
print outer.inner1
print outer.inner2
print outer.inner3
Sometimes you'll also see a pattern of...
class Inner1(object):
pass
class Outer(object):
Inner1 = Inner1
to make a "handy" reference to the class inside the class. This is often used with custom exceptions that the class might throw.
There are many different opinions on whether nesting the classes is preferred.
Honestly inner classes are not generally a good idea, especially if you're instantiating them outside of the "containing" class.
But to answer your question, basically the inner class is just declared in a different scope, so you need to reference the scope it is in.
# Changed to a capitol letter as that is more conventional
class Outer:
name = ""
def __init__(self, name):
self.name = name
def sayHello(self):
print ("Hello" + self.name)
class Inner1:
def __init__(self, name):
self.name = name
class Inner2(Inner1):
pass
class Inner3(Inner1):
pass
newOuter = Outer("newOuter")
newInner2 = Outer.Inner2("newInner2")